您的位置:首页 > 编程语言 > Go语言

Go语言学习之net/url包(url相关操作)(the way to go)

2017-07-12 15:21 561 查看
生命不止,继续 go go go !!!

今天跟大家分享的是是net/url package,从名字已经可以看出来了,与url相关的标准库。

作用:

Package url parses URLs and implements query escaping.

接下来就看看有那些方法:

func QueryEscape

func QueryEscape(s string) string


QueryEscape escapes the string so it can be safely placed inside a URL query.

QueryEscape函数对s进行转码使之可以安全的用在URL查询里。

func QueryUnescape

func QueryUnescape(s string) (string, error)


QueryUnescape does the inverse transformation of QueryEscape, converting %AB into the byte 0xAB and ‘+’ into ’ ’ (space). It returns an error if any % is not followed by two hexadecimal digits.

QueryUnescape函数用于将QueryEscape转码的字符串还原。它会把%AB改为字节0xAB,将’+’改为’ ‘。如果有某个%后面未跟两个十六进制数字,本函数会返回错误。

type Error

type Error struct {
Op string
URL string
Err error
}


Error会报告一个错误,以及导致该错误发生的URL和操作。

type URL

type URL struct {
Scheme string
Opaque string // 编码后的不透明数据
User *Userinfo // 用户名和密码信息
Host string // host或host:port
Path string
RawPath    string // encoded path hint (Go 1.5 and later only; see EscapedPath method)
ForceQuery bool   // append a query ('?') even if RawQuery is empty
RawQuery string // 编码后的查询字符串,没有'?'
Fragment string // 引用的片段(文档位置),没有'#'
}


URL类型代表一个解析后的URL(或者说,一个URL参照)。

URL基本格式如下:

scheme://[userinfo@]host/path[?query][#fragment]

scheme后不是冒号加双斜线的URL被解释为如下格式:

scheme:opaque[?query][#fragment]

func (*URL) Parse

func (u *URL) Parse(ref string) (*URL, error)


Parse parses a URL in the context of the receiver. The provided URL may be relative or absolute. Parse returns nil, err on parse failure, otherwise its return value is the same as ResolveReference.

例子:

package main

import (
"fmt"
"log"
"net/url"
)

func main() {
u, err := url.Parse("http://bing.com/search?q=dotnet")
if err != nil {
log.Fatal(err)
}
fmt.Println(u)
fmt.Println(u.Scheme)
fmt.Println(u.Opaque)
fmt.Println(u.Host)
fmt.Println(u.Path)
fmt.Println(u.RawPath)
fmt.Println(u.ForceQuery)
fmt.Println(u.RawQuery)
fmt.Println(u.Fragment)
}


func ParseRequestURI

func ParseRequestURI(rawurl string) (url *URL, err error)


ParseRequestURI函数解析rawurl为一个URL结构体,本函数会假设rawurl是在一个HTTP请求里,因此会假设该参数是一个绝对URL或者绝对路径,并会假设该URL没有#fragment后缀。(网页浏览器会在去掉该后缀后才将网址发送到网页服务器)

例子:

package main

import (
"fmt"
"net/url"
)

func main() {
values, err := url.ParseRequestURI("https://www.baidu.com/s?wd=%E6%90%9C%E7%B4%A2&rsv_spt=1&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=7&rsv_sug1=6")
fmt.Println(values)
if err != nil {
fmt.Println(err)
}
urlParam := values.RawQuery
fmt.Println(urlParam)

}


func (*URL) IsAbs

func (u *URL) IsAbs() bool


函数在URL是绝对URL时才返回真。

例子:

package main

import (
"fmt"
"net/url"
)

func main() {
url, _ := url.Parse("//example.com")
if url.IsAbs() {
fmt.Printf("%v is absolute.", url)
} else {
fmt.Printf("%v is relative. Are you sure?", url)
}
}


func (*URL) Query

func (u *URL) Query() Values


Query方法解析RawQuery字段并返回其表示的Values类型键值对。

例子:

package main

import (
"fmt"
"net/url"
)

func main() {
u, _ := url.Parse("http://www.example.com/path?foo")
fmt.Println(u)
u.RawQuery = u.Query().Encode()
fmt.Println(u)
}


func (*URL) Port

func (u *URL) Port() string


Port returns the port part of u.Host, without the leading colon. If u.Host doesn’t contain a port, Port returns an empty string.

返回端口号,如果host中没有端口号,接返回一个空的字符串。

例子:

package main

import (
"fmt"
"net/url"
)

func main() {
u, _ := url.Parse("http://www.example.com:8080P/path?foo")
fmt.Println(u.Port())

}


func (*URL) RequestURI

func (u *URL) RequestURI() string


RequestURI方法返回编码好的path?query或opaque?query字符串,用在HTTP请求里。

func (*URL) ResolveReference

func (u *URL) ResolveReference(ref *URL) *URL


ResolveReference resolves a URI reference to an absolute URI from an absolute base URI, per RFC 3986 Section 5.2. The URI reference may be relative or absolute. ResolveReference always returns a new URL instance, even if the returned URL is identical to either the base or reference. If ref is an absolute URL, then ResolveReference ignores base and returns a copy of ref.

本方法根据一个绝对URI将一个URI补全为一个绝对URI,参见RFC 3986 节 5.2。参数ref可以是绝对URI或者相对URI。ResolveReference总是返回一个新的URL实例,即使该实例和u或者ref完全一样。如果ref是绝对URI,本方法会忽略参照URI并返回ref的一个拷贝。

例子:

package main

import (
"fmt"
"log"
"net/url"
)

func main() {
u, err := url.Parse("../../..//search?q=dotnet")
if err != nil {
log.Fatal(err)
}
base, err := url.Parse("http://example.com/directory/")
if err != nil {
log.Fatal(err)
}
fmt.Println(base.ResolveReference(u))
}


type Values

Values maps a string key to a list of values. It is typically used for query parameters and form values. Unlike in the http.Header map, the keys in a Values map are case-sensitive.

Values将建映射到值的列表。它一般用于查询的参数和表单的属性。不同于http.Header这个字典类型,Values的键是大小写敏感的。

type Values map[string][]string


应用:

package main

import (
"fmt"
"net/url"
)

func main() {
v := url.Values{}
v.Set("name", "Ava")
v.Add("friend", "Jess")
v.Add("friend", "Sarah")
v.Add("friend", "Zoe")

fmt.Println(v.Get("name"))
fmt.Println(v.Get("friend"))
fmt.Println(v["friend"])
}


func (Values) Add

func (v Values) Add(key, value string)


Add adds the value to key. It appends to any existing values associated with key.

func (Values) Del

func (v Values) Del(key string)


Del deletes the values associated with key.

func (Values) Encode

func (v Values) Encode() string


Encode encodes the values into “URL encoded” form (“bar=baz&foo=quux”) sorted by key.

func (Values) Get

func (v Values) Get(key string) string


Get gets the first value associated with the given key. If there are no values associated with the key, Get returns the empty string. To access multiple values, use the map directly.

func (Values) Set

func (v Values) Set(key, value string)


Set sets the key to value. It replaces any existing values.

例子:

package main

import (
"fmt"
"net/url"
)

func main() {
c := url.Values{"method": {"get"}, "id": {"1"}}
fmt.Println(c.Encode())
fmt.Println(c.Get("method"))

c.Set("method", "post")
fmt.Println(c.Encode())
fmt.Println(c.Get("method"))

c.Del("method")
fmt.Println(c.Encode())
fmt.Println(c.Get("method"))

c.Add("new", "hi")
fmt.Println(c.Encode())
fmt.Println(c.Encode())
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: