URL Parsing
Parse URLs into components and safely encode query values with net/url.
A URL is a web address, such as https://example.com/search?q=go. The net/url package separates it into parts and safely encodes query values, the text after ?. Parsing only separates the text; it does not show that the address is safe for your program to use.
url.Parse returns fields such as the scheme (https), host (example.com) and path (/search). URL.Query reads values after ?, while url.Values.Encode formats them for a query string.
package main
import (
"fmt"
"net/url"
)
func main() {
u, err := url.Parse("https://example.com/search?q=go")
if err != nil {
fmt.Println("invalid URL:", err)
return
}
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
Before sending a request, check that the scheme is allowed, usually https, and that the host is one your program expects. A well-formed address can still point somewhere you did not intend. Use url.Values to build query values and url.PathEscape to encode one part of a path. Avoid joining user input into a URL by hand.