亲宝软件园·资讯

展开

Go net/url 包

宇宙之一粟 人气:0

引言

在 Golang 中,将 URL 打包用于从服务器获取数据非常重要。只需了解您是否正在处理任何应用程序并且您想从任何外部位置或服务器获取此应用程序的数据,都需要我们可以使用 URL。

URL 格式

URL 包含各种参数:例如 端口、URL 中的搜索字符串等。 URL 可以包含各种方法,允许它处理 URL 属性和进行修改,例如,如果我们有一个类似的 URL www.exmple.com:3000 ,3000 是 URL 的端口,借助 net/url 中的封装函数我们可以访问端口号,同理,还可以检查 URL 格式是否有效。

先来看一下常见 URL 的格式:

<schema>://<user>:<password>@<host>:<port>/<path>:<params>?<query>#<frag>

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 包函数使用格式

Go 的 net/url 提供了众多处理 URL 的内置函数,这些函数的使用格式如下:

URL, error := url.inbuilt-function-name("url")

如何使用 URL 包

在了解 url 包的工作原理之前我们需要了解基本的使用。当我们点击任何 url 时,它可以包含许多属性,比如它可以有一些端口、它可以有一些搜索、它可以有一些路径等,所以我们使用 URL 来操作和处理所有这些东西。让我们了解一下 go 语言中 URL 包 的工作原理。

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 编码

Go 的 net/url 包包含一个名为 QueryEscape 的内置方法,用于对字符串进行转义/编码,以便可以安全地将其放置在 URL 查询中。以下示例演示了如何在 Golang 中对查询字符串进行编码:

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.Values 结构,其中包含查询参数到值的映射,并使用 url.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 编码

就像 QueryEscape 一样,Go 中的 net/url 包有另一个名为 PathEscape() 的函数来对字符串进行编码,以便它可以安全地放置在 URL 的路径段中:

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

加载全部内容

相关教程
猜你喜欢
用户评论