在很多场景中,通过好用的工具操作URL对象比拼接字符串要方便的多。Go标准库提供了维护URL工具,本文通过示例介绍其主要功能。
请看示例:
package main
import (
"encoding/json"
"fmt"
"net/url"
)
func main() {
u := &url.URL{}
u.Scheme = "http"
u.Host = "localhost"
u.Path = "index.html"
u.RawQuery = "id=1&name=jack"
u.User = url.UserPassword("admin", "admin123")
fmt.Printf("\nAssembled URL: %v\n", u)
parsedUrl, err := url.Parse(u.String())
if err != nil {
panic(err)
}
jsonUrl, err := json.Marshal(parsedUrl)
if err != nil {
panic(err)
}
fmt.Printf("Parsed URL: %s", string(jsonUrl))
}
运行结果为:
Assembled URL: http://admin:admin123@localhost/index.html?id=1&name=jack
Get Host localhost from URL Struct
Parsed URL: {"Scheme":"http","Opaque":"","User":{},"Host":"localhost","Path":"/index.html","RawPath":"","OmitHost":false,"ForceQu
ery":false,"RawQuery":"id=1\u0026name=jack","Fragment":"","RawFragment":""}
Process finished with the exit code 0
net/url包用于帮助维护和解析URL对象,URL结构包括必要字段,使用其String方法可以生成url的字符串形式。当需要在字符串形式的url中增加额外操作时,使用Parse函数把字符串转为URL结构类型,从而方便修改。