Skip to main content

URL Parsing

URLs provide a uniform way to locate resources. Here’s how to parse URLs in Go. We’ll parse this example URL, which includes a scheme, authentication info, host, port, path, query params, and query fragment.

To get query params in a string of k=v format, use RawQuery. You can also parse query params into a map. The parsed query param maps are from strings to slices of strings, so index into [0] if you only want the first value.

s := "postgres://user:pass@host.com:5432/path?k=v#f"

u, err := url.Parse(s)
if err != nil {
panic(err)
}

fmt.Println(u.Scheme) // postgres

fmt.Println(u.User) // user
fmt.Println(u.User.Username())
p, _ := u.User.Password() // pass
fmt.Println(p)

fmt.Println(u.Host) // host.com
host, port, _ := net.SplitHostPort(u.Host)
fmt.Println(host)
fmt.Println(port) // 5432

fmt.Println(u.Path) // /path
fmt.Println(u.Fragment)

fmt.Println(u.RawQuery)
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)
fmt.Println(m["k"][0])