URL Parsing
Parse URLs into components and safely encode query values with net/url.
The net/url package separates a URL into components and safely encodes query parameters. Parsing alone does not establish that a URL is valid for your application.
url.Parse returns fields such as scheme, host, and path. URL.Query reads parameters, while url.Values.Encode escapes values when building a query string.
package main
import (
"fmt"
"net/url"
)
func main() {
u, err := url.Parse("https://example.com/search?q=go")
if err != nil {
panic(err)
}
fmt.Println(u.Scheme, u.Host, u.Path, u.Query().Get("q"))
params := url.Values{}
params.Set("q", "go channels")
fmt.Println(params.Encode())
}In production
For outbound requests, validate the scheme and host against what the application permits; a syntactically parseable URL can still target an unsafe destination. Use url.Values for queries and url.PathEscape for individual path segments. Avoid concatenating untrusted strings into URLs.
Enjoyed this? Get more software craft delivered to your inbox.