目录 搜索
archive archive/tar archive/zip bufio bufio(缓存) builtin builtin(内置包) bytes bytes(包字节) compress compress/bzip2(压缩/bzip2) compress/flate(压缩/flate) compress/gzip(压缩/gzip) compress/lzw(压缩/lzw) compress/zlib(压缩/zlib) container container/heap(容器数据结构heap) container/list(容器数据结构list) container/ring(容器数据结构ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(数据库/sql) database/sql/driver(数据库/sql/driver) debug debug/dwarf(调试/dwarf) debug/elf(调试/elf) debug/gosym(调试/gosym) debug/macho(调试/macho) debug/pe(调试/pe) debug/plan9obj(调试/plan9obj) encoding encoding(编码) encoding/ascii85(编码/ascii85) encoding/asn1(编码/asn1) encoding/base32(编码/base32) encoding/base64(编码/base64) encoding/binary(编码/binary) encoding/csv(编码/csv) encoding/gob(编码/gob) encoding/hex(编码/hex) encoding/json(编码/json) encoding/pem(编码/pem) encoding/xml(编码/xml) errors errors(错误) expvar expvar flag flag(命令行参数解析flag包) fmt fmt go go/ast(抽象语法树) go/build go/constant(常量) go/doc(文档) go/format(格式) go/importer go/parser go/printer go/scanner(扫描仪) go/token(令牌) go/types(类型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(图像) image/color(颜色) image/color/palette(调色板) image/draw(绘图) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系统) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路径) plugin plugin(插件) reflect reflect(反射) regexp regexp(正则表达式) regexp/syntax runtime runtime(运行时) runtime/debug(调试) runtime/internal/sys runtime/pprof runtime/race(竞争) runtime/trace(执行追踪器) sort sort(排序算法) strconv strconv(转换) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系统调用) testing testing(测试) testing/iotest testing/quick text text/scanner(扫描文本) text/tabwriter text/template(定义模板) text/template/parse time time(时间戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
文字

  • import "net/url"

  • 概述

  • 索引

  • 示例

概述

url 包解析 URL 并实现查询转义。

索引

  • func PathEscape(s string) string

  • func PathUnescape(s string) (string, error)

  • func QueryEscape(s string) string

  • func QueryUnescape(s string) (string, error)

  • type Error

  • func (e *Error) Error() string

  • func (e *Error) Temporary() bool

  • func (e *Error) Timeout() bool

  • type EscapeError

  • func (e EscapeError) Error() string

  • type InvalidHostError

  • func (e InvalidHostError) Error() string

  • type URL

  • func Parse(rawurl string) (*URL, error)

  • func ParseRequestURI(rawurl string) (*URL, error)

  • func (u *URL) EscapedPath() string

  • func (u *URL) Hostname() string

  • func (u *URL) IsAbs() bool

  • 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

  • func (u *URL) RequestURI() string

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

  • func (u *URL) String() string

  • func (u *URL) UnmarshalBinary(text []byte) error

  • type Userinfo

  • func User(username string) *Userinfo

  • func UserPassword(username, password string) *Userinfo

  • func (u *Userinfo) Password() (string, bool)

  • func (u *Userinfo) String() string

  • func (u *Userinfo) Username() string

  • type Values

  • func ParseQuery(query string) (Values, error)

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

  • func (v Values) Del(key string)

  • func (v Values) Encode() string

  • func (v Values) Get(key string) string

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

示例

ParseQuery URL URL.Hostname URL.RequestURI URL.ResolveReference URL (Roundtrip) Values

文件包

url.go

func PathEscape

func PathEscape(s string) string

PathEscape 会将字符串转义出来,以便将其安全地放置在 URL 路径段中。

func PathUnescape

func PathUnescape(s string) (string, error)

PathUnescape 执行 PathEscape 的逆转换,将 %AB 转换为字节 0xAB 。如果任何 % 之后没有两个十六进制数字,它将返回一个错误。

PathUnescape 与 QueryUnescape 相同,只是它不会将'+'改为''(空格)。

func QueryEscape

func QueryEscape(s string) string

QueryEscape 将字符串转义,以便它可以安全地放置在 URL 查询中。

func QueryUnescape

func QueryUnescape(s string) (string, error)

QueryUnescape 执行 QueryEscape 的逆转换,将 %AB 转换为字节 0xAB ,将'+'转换为''(空格)。如果任何 % 之后没有两个十六进制数字,它将返回一个错误。

type Error

错误报告错误以及导致错误的操作和 URL 。

type Error struct {
        Op  string
        URL string
        Err error}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Temporary

func (e *Error) Temporary() bool

func (*Error) Timeout

func (e *Error) Timeout() bool

type EscapeError

type EscapeError string

func (EscapeError) Error

func (e EscapeError) Error() string

type InvalidHostError

type InvalidHostError string

func (InvalidHostError) Error

func (e InvalidHostError) Error() string

type URL

URL 代表解析的 URL (技术上说,是一个 URI 引用)。

代表的一般形式是:

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

在方案之后不以斜线开头的 URL 被解释为:

scheme:opaque[?query][#fragment]

请注意,路径字段以解码形式存储: /%47%6f%2f 变为 / Go / 。结果是,无法确定路径中的哪些斜杠是原始 URL 中的斜杠,哪些是 %2f 。这种区分很少重要,但是如果是这样,代码不能直接使用 Path 。Parse 函数在它返回的 URL 中设置 Path 和 RawPath ,而 URL 的 String 方法通过调用 EscapedPath 方法使用 RawPath(如果它是 Path 的有效编码)。

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 '#'}

示例

package mainimport ("fmt""log""net/url")func main() {
	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)}

示例(Roundtrip)

package mainimport ("fmt""log""net/url")func main() {// Parse + String preserve the original encoding.
	u, err := url.Parse("https://example.com/foo%2fbar")if err != nil {
		log.Fatal(err)}
	fmt.Println(u.Path)
	fmt.Println(u.RawPath)
	fmt.Println(u.String())}

func Parse

func Parse(rawurl string) (*URL, error)

解析将 rawurl 解析为 URL 结构。Rawurl 可能是相对的或绝对的。

func ParseRequestURI

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

ParseRequestURI 将 rawurl 解析为 URL 结构。它假定 rawurl 是在 HTTP 请求中收到的,所以 rawurl 只被解释为绝对 URI 或绝对路径。字符串 rawurl 假定没有 #fragment 后缀。(在将 URL 发送到 Web 服务器之前,Web 浏览器会去除 #fragment 。)

func (*URL) EscapedPath

func (u *URL) EscapedPath() string

EscapedPath 返回 u.Path 的转义形式。一般来说,任何路径都有多种可能的转义形式。EscapedPath 在 u.Path 有效转义时返回 u.RawPath 。否则,EscapedPath 将忽略 u.RawPath 并自行计算转义表单。 String 和 RequestURI 方法使用 EscapedPath 来构造它们的结果。通常,代码应该调用 EscapedPath ,而不是直接读取 u.RawPath 。

func (*URL) Hostname

func (u *URL) Hostname() string

主机名返回 u.Host ,没有任何端口号。

如果主机是具有端口号的 IPv6 文本,则主机名将返回不带方括号的 IPv6 文字。IPv6 文字可能包含区域标识符。

示例

package mainimport ("fmt""log""net/url")func main() {
	u, err := url.Parse("https://example.org:8000/path")if err != nil {
		log.Fatal(err)}
	fmt.Println(u.Hostname())
	u, err = url.Parse("https://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:17000")if err != nil {
		log.Fatal(err)}
	fmt.Println(u.Hostname())}

func (*URL) IsAbs

func (u *URL) IsAbs() bool

IsAbs 报告 URL 是否是绝对的。绝对意味着它有一个非空的方案。

func (*URL) MarshalBinary

func (u *URL) MarshalBinary() (text []byte, err error)

func (*URL) Parse

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

解析解析接收器上下文中的 URL 。提供的 URL 可能是相对的或绝对的。解析返回 nil ,错误解析失败,否则其返回值与 ResolveReference 相同。

func (*URL) Port

func (u *URL) Port() string

Port 返回 u.Host 的端口部分,不带前导冒号。如果 u.Host 不包含端口,则 Port 返回空字符串。

func (*URL) Query

func (u *URL) Query() Values

查询解析 RawQuery 并返回相应的值。它默默丢弃畸形值对。要检查错误使用 ParseQuery 。

func (*URL) RequestURI

func (u *URL) RequestURI() string

RequestURI 返回在 u 的 HTTP 请求中使用的编码 path?query or opaque?query 字符串。

示例

package mainimport ("fmt""log""net/url")func main() {
	u, err := url.Parse("https://example.org/path?foo=bar")if err != nil {
		log.Fatal(err)}
	fmt.Println(u.RequestURI())}

func (*URL) ResolveReference

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

根据 RFC 3986 第5.2节,ResolveReference 将绝对基 URI 的绝对 URI 解析为 URI 引用。URI 参考可以是相对的或绝对的。即使返回的 URL 与基本或引用完全相同,ResolveReference 也会始终返回新的 URL 实例。如果 ref 是绝对 URL ,则 ResolveReference 将忽略基础并返回 ref 的副本。

示例

package mainimport ("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))}

func (*URL) String

func (u *URL) String() string

字符串将 URL 重组为一个有效的 URL 字符串。结果的一般形式是以下之一:

scheme:opaque?query#fragment
scheme://userinfo@host/path?query#fragment

如果 u.Opaque 不为空,则 String 使用第一种形式; 否则它使用第二种形式。要获取路径,String 使用 u.EscapedPath() 。

在第二种形式中,适用下列规则:

- if u.Scheme is empty, scheme: is omitted.- if u.User is nil, userinfo@ is omitted.- if u.Host is empty, host/ is omitted.- if u.Scheme and u.Host are empty and u.User is nil,
   the entire scheme://userinfo@host/ is omitted.- if u.Host is non-empty and u.Path begins with a /,
   the form host/path does not add its own /.- if u.RawQuery is empty, ?query is omitted.- if u.Fragment is empty, #fragment is omitted.

func (*URL) UnmarshalBinary

func (u *URL) UnmarshalBinary(text []byte) error

type Userinfo

Userinfo 类型是 URL 的用户名和密码详细信息的不可变封装。现有的用户信息值保证具有用户名设置(可能为空,如 RFC 2396 所允许的),并可选择密码。

type Userinfo struct {        // contains filtered or unexported fields}

func User

func User(username string) *Userinfo

用户返回包含提供的用户名和用户密码的用户信息。

func UserPassword

func UserPassword(username, password string) *Userinfo

UserPassword 返回包含提供的用户名和密码的用户信息。

此功能只应与传统网站一起使用。RFC 2396 警告说以这种方式解释用户信息“是不推荐的,因为以明文形式传递验证信息(例如 URI )已被证明在几乎所有已被使用的情况下都具有安全风险。”

func (*Userinfo) Password

func (u *Userinfo) Password() (string, bool)

密码在设置时返回密码,以及是否设置。

func (*Userinfo) String

func (u *Userinfo) String() string

字符串以 “username:password” 的标准格式返回编码后的 userinfo 信息。

func (*Userinfo) Username

func (u *Userinfo) Username() string

Username 返回用户名。

type Values

值将字符串键映射到值列表。它通常用于查询参数和表单值。与 http.Header 映射不同,Values 映射中的键是区分大小写的。

type Values map[string][]string

示例

package mainimport ("fmt""net/url")func main() {
	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"])}

func ParseQuery

func ParseQuery(query string) (Values, error)

ParseQuery 分析 URL 编码的查询字符串并返回一个映射,列出为每个键指定的值。ParseQuery 总是返回一个包含所有找到的有效查询参数的非零映射;err 描述遇到的第一个解码错误,如果有的话。

预计查询是由&符号或分号分隔的键=值设置列表。没有等号的设置被解释为设置为空值的键。

示例

代码:

m, err := url.ParseQuery(`x=1&y=2&y=3;z`)if err != nil {
        log.Fatal(err)}fmt.Println(toJSON(m))

输出:

{"x":["1"], "y":["2", "3"], "z":[""]}

func (Values) Add

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

添加将值添加到键。它附加到与键相关的任何现有值。

func (Values) Del

func (v Values) Del(key string)

Del 删除与键关联的值。

func (Values) Encode

func (v Values) Encode() string

编码将这些值编码为按键排序的“URL编码”形式("bar=baz&foo=quux")。

func (Values) Get

func (v Values) Get(key string) string

获取与给定键相关的第一个值。如果没有与该键关联的值,则 Get 返回空字符串。要访问多个值,请直接使用地图。

func (Values) Set

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

Set 将键设置为值。它取代了现有的任何值。

上一篇: 下一篇: