本篇文章說明 net/url 的部分函式和結構

url.URL

1
2
3
4
5
6
7
8
9
10
11
12
13
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)
OmitHost bool // do not emit empty host (authority)
ForceQuery bool // append a query ('?') even if RawQuery is empty
RawQuery string // encoded query values, without '?'
Fragment string // fragment for references, without '#'
RawFragment string // encoded fragment hint (see EscapedFragment method)
}
1
[scheme:][//[userinfo@]host][/]path[?query][#fragment]

url.URL.Path

1
2
location := url.URL{Path: "/member"}
fmt.Println(location.RequestURI()) // /member

url.URL.RawQuery

1
2
3
4
5
location := url.URL{
Path: "/error",
RawQuery: "message=empty&signal=true",
}
fmt.Println(location.RequestURI()) // /error?message=empty&signal=true

url.Values

1
2
data := url.Values{"message": {"123"}}
fmt.Println(data.Encode()) // message=123

url.Parse

1
2
3
u, _:= url.Parse("https://example.org/error?msg=123")
fmt.Println(u.Path) // /error
fmt.Println(u.RawQuery) // msg=123

Set query string from struct

1
2
3
4
5
6
7
8
9
10
/*** /error?message=empty&signal=true ***/
values := url.Values{
"msg": {"empty"},
"signal": {"true"},
}
location := url.URL{
Path: "/error",
RawQuery: values.Encode(),
}
fmt.Println(location.RequestURI()) // /error?msg=empty&signal=true