Parsing URLs
suggest changeIn Go, URLs and query strings are parsed and manipulated using the standard library net/url package.
Parsing URL Components
Use url.Parse() to parse a raw URL string into a structured *url.URL object:
package main
import (
"fmt"
"net/url"
)
func main() {
raw := "https://admin:secret123@api.example.com:8443/v1/users/search?role=admin&active=true#results"
u, err := url.Parse(raw)
if err != nil {
panic(err)
}
fmt.Printf("Scheme: %s\n", u.Scheme) // https
fmt.Printf("Host: %s\n", u.Host) // api.example.com:8443
fmt.Printf("Hostname: %s\n", u.Hostname()) // api.example.com
fmt.Printf("Port: %s\n", u.Port()) // 8443
fmt.Printf("Path: %s\n", u.Path) // /v1/users/search
fmt.Printf("RawQuery: %s\n", u.RawQuery) // role=admin&active=true
fmt.Printf("Fragment: %s\n", u.Fragment) // results
// User authentication info
if u.User != nil {
username := u.User.Username()
password, hasPassword := u.User.Password()
fmt.Printf("Username: %s, HasPassword: %t (Password: %s)\n", username, hasPassword, password)
}
}
Scheme: https
Host: api.example.com:8443
Hostname: api.example.com
Port: 8443
Path: /v1/users/search
RawQuery: role=admin&active=true
Fragment: results
Username: admin, HasPassword: true (Password: secret123)
Reading and Modifying Query Parameters
The u.Query() method parses the RawQuery into url.Values (a map[string][]string):
package main
import (
"fmt"
"net/url"
)
func main() {
u, _ := url.Parse("https://example.com/search?q=golang&page=1&tag=dev&tag=go")
// Read query parameters
params := u.Query()
fmt.Println("Search term:", params.Get("q")) // golang
fmt.Println("Page:", params.Get("page")) // 1
fmt.Println("All tags:", params["tag"]) // [dev go]
fmt.Println("Has filter:", params.Has("filter")) // false
// Modify query parameters
params.Set("page", "2") // Replaces any existing "page" values
params.Add("tag", "web") // Appends another value for "tag"
params.Del("q") // Removes parameter
// Encode values and assign back to URL
u.RawQuery = params.Encode()
fmt.Println("Updated URL:", u.String())
}
Search term: golang
Page: 1
All tags: [dev go]
Has filter: false
Updated URL: https://example.com/search?page=2&tag=dev&tag=go&tag=web
Constructing URLs Safely
1. url.JoinPath (Go 1.19+)
url.JoinPath concatenates URL paths cleanly, ensuring slashes are normalized without duplicating or stripping them:
package main
import (
"fmt"
"net/url"
)
func main() {
fullURL, err := url.JoinPath("https://api.example.com/base/", "/v2/", "products", "123")
if err != nil {
panic(err)
}
fmt.Println(fullURL) // https://api.example.com/base/v2/products/123
}
2. Resolving Relative URLs (ResolveReference)
To resolve a relative link (such as from an HTML <a href="...">) against a base page URL:
package main
import (
"fmt"
"net/url"
)
func main() {
base, _ := url.Parse("https://example.com/blog/posts/index.html")
relative, _ := url.Parse("../../images/logo.png")
resolved := base.ResolveReference(relative)
fmt.Println(resolved.String()) // https://example.com/images/logo.png
}
Escaping and Unescaping Strings
For manual parameter or path segment escaping:
package main
import (
"fmt"
"net/url"
)
func main() {
query := "hello world & more?"
escaped := url.QueryEscape(query)
fmt.Println("Escaped:", escaped) // hello+world+%26+more%3F
unescaped, _ := url.QueryUnescape(escaped)
fmt.Println("Unescaped:", unescaped) // hello world & more?
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents