GO語言"net/url"包中"URL"類型的用法及代碼示例。
URL 表示已解析的 URL(從技術上講,是 URI 引用)。
表示的一般形式是:
用法:
[scheme:][//[userinfo@]host][/]path[?query][#fragment]
方案後不以斜杠開頭的 URL 被解釋為:
scheme:opaque[?query][#fragment]
請注意,路徑字段以解碼形式存儲:/%47%6f%2f 變為 /Go/。結果是無法分辨路徑中的哪些斜杠是原始 URL 中的斜杠,哪些是 %2f。這種區別很少重要,但當它重要時,代碼應該使用 RawPath 一個可選字段,隻有在默認編碼與路徑不同時才會設置該字段。
URL 的 String 方法使用EscapedPath 方法獲取路徑。有關詳細信息,請參閱EscapedPath 方法。
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); added in Go 1.5 ForceQuery bool // append a query ('?') even if RawQuery is empty; added in Go 1.7 RawQuery string // encoded query values, without '?' Fragment string // fragment for references, without '#' RawFragment string // encoded fragment hint (see EscapedFragment method); added in Go 1.15 }
例子:
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)
}
u.Scheme = "https"
u.Host = "google.com"
q := u.Query()
q.Set("q", "golang")
u.RawQuery = q.Encode()
fmt.Println(u)
}
輸出:
https://google.com/search?q=golang
示例(往返):
package main
import (
"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())
}
輸出:
/foo/bar /foo%2fbar https://example.com/foo%2fbar
相關用法
- GO URL.Hostname用法及代碼示例
- GO URL.EscapedPath用法及代碼示例
- GO URL.Port用法及代碼示例
- GO URL.ResolveReference用法及代碼示例
- GO URL.Query用法及代碼示例
- GO URL.Redacted用法及代碼示例
- GO URL.Parse用法及代碼示例
- GO URL.String用法及代碼示例
- GO URL.UnmarshalBinary用法及代碼示例
- GO URL.EscapedFragment用法及代碼示例
- GO URL.MarshalBinary用法及代碼示例
- GO URL.RequestURI用法及代碼示例
- GO URL.IsAbs用法及代碼示例
- GO UDPConn.WriteTo用法及代碼示例
- GO Unmarshal用法及代碼示例
- GO UnaryOp用法及代碼示例
- GO Unsetenv用法及代碼示例
- GO Unquote用法及代碼示例
- GO Unwrap用法及代碼示例
- GO UnquoteChar用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 URL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。