引言
在 Golang 中,将 URL 打包用于从服务器获取数据非常重要。只需了解您是否正在处理任何应用程序并且您想从任何外部位置或服务器获取此应用程序的数据,都需要我们可以使用 URL。
URL 格式
www.exmple.com:3000net/url
先来看一下常见 URL 的格式:
<schema>://<user>:<password>@<host>:<port>/<path>:<params>?<query>#<frag>
schemeURLuserpasswordhostIPportpathURLparamsURLqueryfragURLHTML
HTTP
对应 Go 中 URL 的结构体:
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 '#'
RawFragment string // encoded fragment hint (see EscapedFragment method)
}
Go url 包函数使用格式
net/url
URL, error := url.inbuilt-function-name("url")
ParsePathRawpathstring()
如何使用 URL 包
urlurlURL
package main
import (
"fmt"
"log"
"net/url"
)
func TestURL() {
URL, err := url.Parse("https://www.baidu.com/s?wd=golang")
fmt.Println("Url before modification is", URL)
if err != nil {
log.Fatal("An error occurs while handling url", err)
}
URL.Scheme = "https"
URL.Host = "bing.com"
query := URL.Query()
query.Set("q", "go")
URL.RawQuery = query.Encode()
fmt.Println("The url after modification is", URL)
}
func main() {
TestURL()
}
运行结果:
$ go run main.go
Url before modification is https://www.baidu.com/s?wd=golang
The url after modification is https://bing.com/s?q=go&wd=golang
在 Golang 中对查询字符串进行 URL 编码
net/urlQueryEscape
package main
import (
"fmt"
"net/url"
)
func main() {
query := "Hello World"
fmt.Println(url.QueryEscape(query))
}
运行结果:
$ go run main.go
Hello+World
在 Golang 中对多个查询参数进行 URL 编码
url.Valuesurl.Values.Encode()
package main
import (
"fmt"
"net/url"
)
func main() {
params := url.Values{}
params.Add("name", "@Wade")
params.Add("phone", "+111111111111")
fmt.Println(params.Encode())
}
运行代码:
$ go run main.go
name=%40Wade&phone=%2B111111111111
在 Golang 中对路径段进行 URL 编码
QueryEscapenet/urlPathEscape()
package main
import (
"fmt"
"net/url"
)
func main() {
path := "path with?reserved+characters"
fmt.Println(url.PathEscape(path))
}
运行结果:
$ go run main.go
path%20with%3Freserved+characters
通过对各个部分进行编码来构建完整的 URL
最后,我们来看一个完整的 Golang 中 URL 解析和 URL 编码的例子:
package main
import (
"fmt"
"net/url"
)
func main() {
// Let's start with a base url
baseUrl, err := url.Parse("http://www.bing.com")
if err != nil {
fmt.Println("Malformed URL: ", err.Error())
return
}
// Add a Path Segment (Path segment is automatically escaped)
baseUrl.Path += "path with?reserved characters"
// Prepare Query Parameters
params := url.Values{}
params.Add("q", "Hello World")
params.Add("u", "@wade")
// Add Query Parameters to the URL
baseUrl.RawQuery = params.Encode() // Escape Query Parameters
fmt.Printf("Encoded URL is %q\n", baseUrl.String())
}
运行代码:
$ go run main.go
Encoded URL is "http://www.bing.com/path%20with%3Freserved%20characters?q=Hello+World&u=%40wade"
在 Golang 中解析 URL
package main
import (
"fmt"
"log"
"net/url"
)
func TestURL() {
URL, err := url.Parse("http://bing.com/good%2bad")
fmt.Println("Url before modification is", URL)
if err != nil {
log.Fatal("An error occurs while handling url", err)
}
fmt.Println("The URL path is", URL.Path)
fmt.Println("The URL raw path is", URL.RawPath)
fmt.Println("The URL is ", URL.String())
}
func main() {
TestURL()
}
运行代码:
$ go run main.go
Url before modification is http://bing.com/good%2bad
The URL path is /good+ad
The URL raw path is /good%2bad
The URL is http://bing.com/good%2bad
处理相对路径
package main
import (
"fmt"
"log"
"net/url"
)
func ExampleURL() {
URL, error := url.Parse("../../..//search?q=php")
fmt.Println("Url before modification is", URL)
if error != nil {
log.Fatal("An error occurs while handling url", error)
}
baseURL, err := url.Parse("http://example.com/directory/")
if err != nil {
log.Fatal("An error occurs while handling url", err)
}
fmt.Println(baseURL.ResolveReference(URL))
}
func main() {
ExampleURL()
}
$ go run main.go
Url before modification is ../../..//search?q=php
http://example.com/search?q=php
解析空格
package main
import (
"fmt"
"log"
"net/url"
)
func ExampleURL() {
URL, error := url.Parse("http://example.com/Here path with space")
if error != nil {
log.Fatal("An error occurs while handling url", error)
}
fmt.Println("The Url is", URL)
}
func main() {
ExampleURL()
}
运行结果:
$ go run main.go
The Url is http://example.com/Here%20path%20with%20space
判断绝对地址
package main
import (
"fmt"
"net/url"
)
func main() {
u := url.URL{Host: "example.com", Path: "foo"}
fmt.Println("The Url is", u.IsAbs())
u.Scheme = "http"
fmt.Println("The Url is", u.IsAbs())
}
$ go run main.go
The Url is false
The Url is true
解析端口
package main
import (
"fmt"
"log"
"net/url"
)
func ExampleURL() {
URL1, error := url.Parse("https://example.org")
fmt.Println("URL1 before modification is", URL1)
if error != nil {
log.Fatal("An error occurs while handling url", error)
}
URL2, err := url.Parse("https://example.org:8080")
if err != nil {
log.Fatal("An error occurs while handling url", URL2)
}
fmt.Println("URL2 before modification is", URL2)
fmt.Println("URL2 Port number is", URL2.Port())
}
func main() {
ExampleURL()
}
$ go run main.go
URL1 before modification is https://example.org
URL2 before modification is https://example.org:8080
URL2 Port number is 8080
到此这篇关于Golang 入门之ur l 包的文章就介绍到这了!