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.
Code
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
URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.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.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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):`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.