Go

net/url — Build Query Strings Safely

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Stop concatenating `?a=1&b=2` by hand. `url.Values` (a `map[string][]string`) escapes correctly, handles repeated keys, and `url.URL.String()` renders the canonical form.
Go
Raw
package main

import (
    "fmt"
    "net/url"
)

func main() {
    // Build from scratch
    u := url.URL{
        Scheme: "https",
        Host:   "api.example.com",
        Path:   "/users",
    }
    q := u.Query()
    q.Set("active", "true")
    q.Add("role", "admin")
    q.Add("role", "editor")                       // repeated key — fine
    q.Set("q", "hello world & friends")           // spaces and & properly escaped
    u.RawQuery = q.Encode()
    fmt.Println(u.String())
    // https://api.example.com/users?active=true&q=hello+world+%26+friends&role=admin&role=editor

    // Parse an existing URL
    parsed, _ := url.Parse("https://api.example.com/users?id=42")
    fmt.Println(parsed.Host)                      // api.example.com
    fmt.Println(parsed.Query().Get("id"))         // 42
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.