How to Parse a URL in Go?

Parsing a URL in Go is straightforward with the net/url package. Here's a step-by-step guide on how to do it:

  1. Importing the net/url Package
import "net/url"
  1. Creating a URL Object
u, err := url.Parse("https://example.com/path?name=value#hash")
if err != nil {
    log.Fatal(err)
}
  1. Accessing URL Components
fmt.Println(u.Scheme)  // Output: https
fmt.Println(u.Host)    // Output: example.com
fmt.Println(u.Path)    // Output: /path
fmt.Println(u.RawQuery)// Output: name=value
fmt.Println(u.Fragment)// Output: hash
  1. Working with URL Parameters
// Get a map of URL parameters
m, _ := url.ParseQuery(u.RawQuery)
for k, v := range m {
    fmt.Printf("%s: %s\n", k, v[0])
}
  1. Modifying and Reconstructing URLs
// Create a new URL with modified components
newURL := &url.URL{
    Scheme: u.Scheme,
    Host: u.Host,
    Path: "/newpath",
    RawQuery: u.RawQuery,
    Fragment: u.Fragment,
}
fmt.Println(newURL.String())  // Output: https://example.com/newpath?name=value#hash

With the net/url package, parsing a URL in Go is simple and intuitive, allowing you to access, analyze, and modify URLs with ease.

Lastly, if you want to grab query parameters from any url without using go, use parseurlonline.com to quickly get the data without any hassle.