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.

GoData Fetching

Code

gosnippet
24 lines
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

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.