Golang 入门 之url 包


Posted in Golang onMay 04, 2022

引言

在 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>

  • scheme : 方案是如何访问指定资源的主要标识符,他会告诉负责解析 URL 应用程序应该使用什么协议;
  • user :用户名;
  • password :密码;
  • host : 主机组件标识了因特网上能够访问资源的宿主机器,可以有主机名或者是 IP 地址来表示;
  • port : 端口标识了服务器正在监听的网络端口。默认端口号是 80;
  • path : URL 的路径组件说明了资源位于服务器的什么地方;
  • params : URL 中通过协议参数来访问资源,比名值对列表,分号分割来进行访问;
  • query : 字符串是通过提问问题或进行查询来缩小请求资源类的范围;
  • frag : 为了引用部分资源或资源的一个片段,比如 URL 指定 HTML 文档中一个图片或一个小节;

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 的一些基本细节。我们可以给它起任何名字。它就像任何变量一样。
  • error: 这是 error 部分,以防 URL 错误或出现任何异常,在这种情况下 URL 将返回错误,并且该 error 将在 error 部分中捕获。
  • inbuilt-function-name:正如我们所讨论的,URL 包中有许多函数可以处理 URL,例如 ParsePathRawpathstring() 所有这些函数我们可以用于不同的目的。

如何使用 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

到此这篇关于Golang 入门之ur l 包的文章就介绍到这了!

Golang 相关文章推荐
浅谈Golang 嵌套 interface 的赋值问题
Apr 29 Golang
Go 在 MongoDB 中常用查询与修改的操作
May 07 Golang
基于Golang 高并发问题的解决方案
May 08 Golang
Go语言实现Snowflake雪花算法
Jun 08 Golang
go web 预防跨站脚本的实现方式
Jun 11 Golang
再次探讨go实现无限 buffer 的 channel方法
Jun 13 Golang
Go 语言下基于Redis分布式锁的实现方式
Jun 28 Golang
go goroutine 怎样进行错误处理
Jul 16 Golang
基于Go语言构建RESTful API服务
Jul 25 Golang
一文搞懂Golang 时间和日期相关函数
Dec 06 Golang
golang语言指针操作
Apr 14 Golang
Golang实现可重入锁的示例代码
May 25 Golang
Golang解析JSON对象
Apr 30 #Golang
Golang 并发编程 SingleFlight模式
Golang 实现 WebSockets 之创建 WebSockets
Apr 24 #Golang
Golang 实现WebSockets
Golang ort 中的sortInts 方法
Apr 24 #Golang
Golang 切片(Slice)实现增删改查
Apr 22 #Golang
Golang 结构体数据集合
Apr 22 #Golang
You might like
PHP 编写的 25个游戏脚本
2009/05/11 PHP
Ajax提交表单时验证码自动验证 php后端验证码检测
2016/07/20 PHP
在网页中使用document.write时遭遇的奇怪问题
2010/08/24 Javascript
jquery ready(fn)事件使用介绍
2013/08/21 Javascript
jquery组件使用中遇到的问题整理及解决
2014/02/21 Javascript
跟我学习javascript的prototype使用注意事项
2015/11/17 Javascript
JS组件Bootstrap Select2使用方法解析
2016/05/30 Javascript
Bootstrap导航条可点击和鼠标悬停显示下拉菜单的实现代码
2016/06/23 Javascript
把json格式的字符串转换成javascript对象或数组的方法总结
2016/11/03 Javascript
微信小程序之ES6与事项助手的功能实现
2016/11/30 Javascript
Spring shiro + bootstrap + jquery.validate 实现登录、注册功能
2017/06/02 jQuery
微信小程序Redux绑定实例详解
2017/06/07 Javascript
javascript实现获取一个日期段内每天不同的价格(计算入住总价格)
2018/02/05 Javascript
layui 弹出层回调获取弹出层数据的例子
2019/09/02 Javascript
vue ssr服务端渲染(小白解惑)
2019/11/10 Javascript
jQuery 动态粒子效果示例代码
2020/07/07 jQuery
[42:32]VP vs RNG 2019国际邀请赛淘汰赛 败者组 BO3 第一场 8.21.mp4
2020/07/19 DOTA
在Python中使用next()方法操作文件的教程
2015/05/24 Python
Python简单删除目录下文件以及文件夹的方法
2015/05/27 Python
Python运行报错UnicodeDecodeError的解决方法
2016/06/07 Python
python TK库简单应用(实时显示子进程输出)
2019/10/29 Python
python opencv将表格图片按照表格框线分割和识别
2019/10/30 Python
带你彻底搞懂python操作mysql数据库(cursor游标讲解)
2020/01/06 Python
Python基于爬虫实现全网搜索并下载音乐
2021/02/14 Python
纯CSS实现菜单、导航栏的3D翻转动画效果
2014/04/23 HTML / CSS
法国票务网站:Ticketmaster法国
2018/07/09 全球购物
建筑工程毕业生自我鉴定
2014/01/14 职场文书
公司户外活动总结
2014/07/04 职场文书
客户答谢会活动方案
2014/08/31 职场文书
拾金不昧感谢信范文
2015/01/21 职场文书
生产车间主任岗位职责
2015/04/08 职场文书
幼儿园六一主持词开场白
2015/05/28 职场文书
Go语言实现Base64、Base58编码与解码
2021/07/26 Golang
解决使用了nginx获取IP地址都是127.0.0.1 的问题
2021/09/25 Servers
分享node.js实现简单登录注册的具体代码
2022/04/26 NodeJs
JS精髓原型链继承及构造函数继承问题纠正
2022/06/16 Javascript