PathEscape Versus QueryEscape

Pick url.PathEscape for a single path segment and url.QueryEscape for a query value, since the two sets of reserved characters differ.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// 用户可控的 ID:内含 / 与 ? 时会改变 URL 结构,必须先转义
	id := "reports/2026 Q4?sort=asc"

	// PathEscape 面向单个路径段:/ 与 ? 都编码,空格变 %20
	seg := url.PathEscape(id)
	fmt.Println("path segment:", seg)

	// QueryEscape 面向查询值:空格变 +,语义等价但对 query 更紧凑
	fmt.Println("query value:", url.QueryEscape(id))

	// 未转义直接拼接:多出来的 / 会把路径切成更多层级
	fmt.Println("raw (wrong):", "/api/files/"+id)
	fmt.Println("escaped (ok):", "/api/files/"+seg)

	// 解析后校验:转义正确时 Path 里只有一个额外层级
	u, err := url.Parse("/api/files/" + seg)
	if err != nil {
		fmt.Println("parse:", err)
		return
	}
	fmt.Println("parsed path:", u.Path)

	// QueryUnescape 是逆操作:把 + 还原成空格
	back, err := url.QueryUnescape(url.QueryEscape(id))
	fmt.Println("roundtrip:", back == id, "err:", err)
}

Two escape functions side by side

The main function holds every step of the comparison; nothing else defines behavior.

Nothing falls through silently — 1 checkpoint test err != nil on the way through.

Watch out for

  • The only import is net/url, which is part of the standard distribution.

Applying it

The entry point is func main()

Each stage tags its own line — path segment:, query value:, raw (wrong): — so the contrast reads directly off the output.

The comparisons that matter

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

Interactive Tools for This Topic

FAQ

What does PathEscape Versus QueryEscape print when run?
Execute the whole file; each printed line is prefixed with a label like `path segment:`, `query value:`, `raw (wrong):`.