URL Values Encode Query Parameters
Build query strings with url.Values: Encode percent-escapes values and sorts keys deterministically, while ParseQuery decodes raw query strings back.
Code
package main
import (
"fmt"
"net/url"
)
func main() {
// url.Values is a map[string][]string; Encode emits keys in sorted order
q := url.Values{}
q.Set("lang", "zh-cn")
q.Add("tag", "go")
q.Add("tag", "rust")
fmt.Println(q.Encode())
// Special characters are percent-escaped automatically: & becomes %26 and a space becomes +
q.Set("q", "gopher & postgres")
fmt.Println(q.Encode())
// In reverse: ParseQuery decodes a query string back into Values, keeping repeated keys
parsed, err := url.ParseQuery("a=1&b=x&b=y")
if err != nil {
panic(err)
}
fmt.Println("b:", parsed["b"])
// Get returns the first value; a missing key yields an empty string instead of an error
fmt.Printf("a=%q missing=%q\n", parsed.Get("a"), parsed.Get("nope"))
}What the code does
URL Values Encode Query Parameters keeps everything in the function main.
Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.
What to watch for
- The runtime is the only requirement — no packages, no install.
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Applying it
The file announces its steps in the output: b:, a=.
Statements that matter
if err != nil {
panic(err)
}
Interactive Tools for This Topic
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Encoder & DecoderEncode and decode URLs and their components safely. Switch between encodeURIComponent and encodeURI modes to handle query parameters, paths, and special characters.URL Query String SerializerParse a URL query string into decoded key/value pairs or serialize key=value lines into a percent-encoded query string with duplicate-key detection.
FAQ
- How should callers handle failures?
- By terminating the run: `panic(err)` fires at each of the 1 check, so callers see failures only as a stopped program.
- What does URL Values Encode Query Parameters print when run?
- Running the file directly is enough — expect labeled output lines such as `b:`, `a=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.