go标准库 net/url


go标准库 net/url包 解析URL并实现查询转义 $GOROOT\src\net\url
import "net/url" url包 解析URL并实现查询转义
URL 结构体
// Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/.
// A consequence is that it is impossible to tell which slashes in the Path were
// slashes in the raw URL and which were %2f. This distinction is rarely important,
// but when it is, code must not use Path directly.
// The Parse function sets both Path and RawPath in the URL it returns,
// and URL's String method uses RawPath if it is a valid encoding of Path,
// by calling the EscapedPath method.
type URL struct {
    Scheme     string
    Opaque     string    // encoded opaque data
    User       *Userinfo // username and password information
    Host       string    // host or host:port
    Path       string    // path (relative paths may omit leading slash)
    RawPath    string    // encoded path hint (see EscapedPath method)
    ForceQuery bool      // append a query ('?') even if RawQuery is empty
    RawQuery   string    // encoded query values, without '?'
    Fragment   string    // fragment for references, without '#'
}
func Parse(rawurl string) (*URL, error)
将原生的 rawurl 字符串解析成URL结构体
package main
import (
    "fmt"
    "log"
    "net/url"
)
func main() {
    u, err := url.Parse("http://www.doamin.com/search?q=dotnet")
    if err != nil {
        log.Fatal(err)
    }
    u.Scheme = "https"
    u.Host = "google.com"
    q := u.Query()
    q.Set("q", "golang")
    u.RawQuery = q.Encode()
    fmt.Println(u)
}// https://google.com/search?q=golang
URL 格式
scheme://[userinfo]@[host]:[port]/path?key1=value1&key2=value2#fragment
协议 http, https, file, ftp  用户信息 是可选
主机名字或者ip地址 定位网络位置
port 服务端口 一般端口表示提供了某项服务
path 主机上的目录
?后的问query信息  key1=value1是表示key值和value值 &是连接符
# 后面的是fragment信息
URL处理非ascii编码
非ascii编码 使用%后跟两位16进制数表示 如%AB
URL中不能有空格 空格用 + 表示
url 库
url path字段中有空格和非ascii字符
func PathEscape(s string) string
返回的string将是url可以使用的%后跟两位16进制数的形式
如何把url中的path字段还原成原始模式
func PathUnescape(s string) (string, err)
a := "hello, 世界" //contain non-ascii code
b := url.PathEscape(a)
fmt.Printf("%v\n", b)// Output: hello%2C%20%E4%B8%96%E7%95%8C
c, _ := url.PathUnescape(b)
fmt.Printf("%v\n", c)// Output: hello, 世界
Note: path中的空格和非ascii字符使用同样的方式处理。
query字段中出现非ascii字符和空格如何处理
func QueryEscape(s string) string
func QueryEscape(s string) (string, error)
处理Query 数据
Query字段可以通过ParseQuery函数来处理 ParseQuery根据传入的字符串 生成一个Values字典
type Values map[string][]string


go标准库 net/url和net-url相关