URL ParseQuery Rejects Malformed Input
Parse query strings with url.ParseQuery and surface malformed input: bare semicolons and invalid percent escapes return errors instead of dirty data.
Code
package main
import (
"fmt"
"net/url"
)
func main() {
// 正常输入:解成多值映射,重复键保留为切片
q, err := url.ParseQuery("lang=go&page=2&tag=std&tag=json")
if err != nil {
panic(err)
}
fmt.Println("lang:", q.Get("lang"), "page:", q.Get("page"))
fmt.Println("tags:", q["tag"])
// 裸分号 malformed input 被拒绝:避免与 & 的歧义被静默吞掉
_, semiErr := url.ParseQuery("a=1;b=2")
fmt.Println("semicolon error:", semiErr != nil)
// 非法百分号转义同样报错,而不是解析出脏数据
_, escErr := url.ParseQuery("q=%zz")
fmt.Println("escape error:", escErr != nil)
}How it works
URL ParseQuery Rejects Malformed Input is built around 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
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Applying it
Output lines are prefixed (lang:, tags:, semicolon error:), so the effect of every operation can be spotted in the printed lines.
Statements that matter
if err != nil {
panic(err)
}
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.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
FAQ
- What happens when a call fails?
- There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
- What does URL ParseQuery Rejects Malformed Input print when run?
- Invoke the file as-is — the `lang:`, `tags:`, `semicolon error:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.