URL Parse Splits Request Components
Break a URL into scheme, host, path, and query with net/url.Parse, and rebuild or modify components through the returned struct instead of string surgery.
Code
package main
import (
"fmt"
"net/url"
)
func main() {
raw := "https://api.example.com:8443/v2/orders?limit=10&sort=desc"
u, err := url.Parse(raw)
if err != nil {
fmt.Println("parse error:", err)
return
}
// 各组件都是结构体字段:读取零成本,修改也无需字符串切割
fmt.Println("scheme:", u.Scheme)
fmt.Println("host :", u.Host, "port:", u.Port())
fmt.Println("path :", u.Path)
fmt.Println("query :", u.RawQuery)
// Query() 返回 Values:多值键、顺序敏感场景用它
q := u.Query()
q.Set("limit", "25")
q.Del("sort")
u.RawQuery = q.Encode()
fmt.Println("rebuilt:", u.String())
}What the code does
URL Parse Splits Request Components is built around the function main.
Nothing falls through silently — 1 checkpoint test err != nil on the way through.
Applying it
The demo output is labeled (parse error:, scheme:, host :), so the printed output reads as a trace of the operations performed.
Statements that matter
if err != nil {
fmt.Println("parse error:", err)
return
}
Interactive Tools for This Topic
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.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.Nano ID GeneratorGenerate URL-safe Nano ID strings with a configurable length and alphabet using the Web Crypto API.
FAQ
- What does URL Parse Splits Request Components print when run?
- The script runs standalone; its 6 labeled outputs include `parse error:`, `scheme:`, `host :`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.