當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO URL.String用法及代碼示例

GO語言"net/url"包中"URL.String"類型的用法及代碼示例。

用法:

func(u *URL) String() string

String 將 URL 重新組合成一個有效的 URL 字符串。結果的一般形式是以下之一:

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

如果 u.Opaque 非空,String 使用第一種形式;否則它使用第二種形式。主機中的任何非 ASCII 字符都會被轉義。為了獲取路徑,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.

例子:

package main

import (
	"fmt"
	"net/url"
)

func main() {
	u := &url.URL{
		Scheme:   "https",
		User:     url.UserPassword("me", "pass"),
		Host:     "example.com",
		Path:     "foo/bar",
		RawQuery: "x=1&y=2",
		Fragment: "anchor",
	}
	fmt.Println(u.String())
	u.Opaque = "opaque"
	fmt.Println(u.String())
}

輸出:

https://me:pass@example.com/foo/bar?x=1&y=2#anchor
https:opaque?x=1&y=2#anchor

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 URL.String。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。