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.

GoData Fetching

Code

snippet
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

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=`.