Go URL Parsing
URLs consist of many parts like scheme, host, path, and query parameters. Go's net/url package makes it easy to extract or build them.
1. Parsing a URL
Use url.Parse to break a string into its components.
| package main
import (
"fmt"
"net"
"net/url"
)
func main() {
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:pass
fmt.Println(u.Host) // host.com:5432
fmt.Println(u.Path) // /path
fmt.Println(u.Fragment) // f
// To get user/pass details:
fmt.Println(u.User.Username())
p, _ := u.User.Password()
fmt.Println(p)
// To get host/port separately:
host, port, _ := net.SplitHostPort(u.Host)
fmt.Println(host) // host.com
fmt.Println(port) // 5432
}
|
2. Query Parameters
The u.RawQuery returns a string. To work with it as a map, use u.Query().
| fmt.Println(u.RawQuery) // k=v
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m) // map[k:[v]]
fmt.Println(m["k"][0]) // v
|
3. Building a URL
You can also go the other way—building a URL from scratch.
| values := url.Values{}
values.Add("q", "golang")
values.Add("page", "1")
u := &url.URL{
Scheme: "https",
Host: "google.com",
Path: "search",
RawQuery: values.Encode(),
}
fmt.Println(u.String()) // https://google.com/search?page=1&q=golang
|
Why use net/url?
- Correctness: It handles complex rules about what characters are allowed where (e.g., spaces vs
%20).
- Security: It prevents "injection" attacks by properly escaping user input.
- Cross-platform: It follows universal standards for web addresses.