url
最后更新于:2022-04-02 02:45:09
[TOC]
## 语法
```
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)
func ParseRequestURI(rawurl string) (*URL, error)
func (u *URL) EscapedFragment() string
func (u *URL) EscapedPath() string // 转义路径,已经转义的将不转义
func (u *URL) Hostname() string
func (u *URL) IsAbs() bool // 是否是绝对路径 协议加域名就返回true
func (u *URL) MarshalBinary() (text []byte, err error)
func (u *URL) Parse(ref string) (*URL, error) // 在原始域名上添加新的参数
func (u *URL) Port() string
func (u *URL) Query() Values // 返回 url.Valus
func (u *URL) RequestURI() string // 返回 path?query 的部分
func (u *URL) ResolveReference(ref *URL) *URL // 并接两个url
func (u *URL) String() string
func (u *URL) UnmarshalBinary(text []byte) error
```
## url.Values
```
v := url.Values{}
v.Set("name", "Ava")
v.Add("friend", "Jess")
v.Add("friend", "Sarah")
v.Add("friend", "Zoe")
// v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"
fmt.Println(v.Get("name"))
fmt.Println(v.Get("friend"))
fmt.Println(v["friend"])
// Output:
// Ava
// Jess
// [Jess Sarah Zoe]
```
## url.Parse()
```
u, err := url.Parse("http://bing.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)
// Output: https://google.com/search?q=golang
```
## PathEscape/ PathUnescape 只转义path
```
escape := url.PathEscape("/a/b")
fmt.Printf("%+v\n", escape) // %2Faasd%2Fasd
unescape, _ := url.PathUnescape("%2Faasd%2Fasd")
fmt.Printf("%+v\n", unescape) // /aasd/asd
```
## QueryEscape / QueryUnEscape 转移完整url
';