Parse And Rebuild URL Query Strings

Parse a URL into components, mutate the query with url.Values Add, Set, and Del, then re-encode it — with QueryEscape for free-form text values.

GoData Fetching

Code

gosnippet
33 lines
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// Parse:拆出 scheme、host、path 与查询参数
	endpoint := "https://api.example.com/v1/orders?status=open&limit=10"
	parsed, err := url.Parse(endpoint)
	if err != nil {
		fmt.Println("bad url:", err)
		return
	}
	fmt.Println("host:", parsed.Host, "path:", parsed.Path)

	// Query 解析查询串,畸形部分被静默丢弃
	query := parsed.Query()
	query.Add("status", "closed") // Add 追加同名键
	query.Set("limit", "50")      // Set 覆盖全部同名键
	parsed.RawQuery = query.Encode()
	fmt.Println("rebuilt:", parsed.String())

	// 自由文本进查询串前必须转义
	fmt.Println("escaped:", url.QueryEscape("go & rust?"))
	value, err := url.QueryUnescape("go%20%26+rust%3F")
	if err != nil {
		fmt.Println("unescape:", err)
		return
	}
	fmt.Println("unescaped:", value)
}

What the code does

Parse And Rebuild URL Query Strings is built around the function main.

Nothing falls through silently — 2 checkpoints test err != nil on the way through.

Applying it

Running the file prints labeled results such as bad url:, host:, rebuilt: — each operation’s effect is visible in the output.

Statements that matter

if err != nil {
fmt.Println("bad url:", err)
return
}
if err != nil {
fmt.Println("unescape:", err)
return
}

Interactive Tools for This Topic

FAQ

What does Parse And Rebuild URL Query Strings print when run?
Run it as a complete program — the output lines carry labels such as `bad url:`, `host:`, `rebuilt:`.