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.
Code
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
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 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.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.