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.

GoData Fetching

Code

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

FAQ

What does URL Parse Splits Request Components print when run?
The script runs standalone; its 6 labeled outputs include `parse error:`, `scheme:`, `host :`.