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如何替换某个文件中的字符串
Apr 25 Golang
基于Go Int转string几种方式性能测试
Apr 28 Golang
golang 比较浮点数的大小方式
May 02 Golang
解决goland 导入项目后import里的包报红问题
May 06 Golang
关于golang高并发的实现与注意事项说明
May 08 Golang
go xorm框架的使用
May 22 Golang
K8s部署发布Golang应用程序的实现方法
Jul 16 Golang
Go语言基础切片的创建及初始化示例详解
Nov 17 Golang
简单聊聊Golang中defer预计算参数
Mar 25 Golang
GoFrame gredis缓存DoVar Conn连接对象 自动序列化GoFrame gredisDo/DoVar方法Conn连接对象自动序列化/反序列化总结
Jun 14 Golang
Go 内联优化让程序员爱不释手
Jun 21 Golang
Go gorilla securecookie库的安装使用详解
Aug 14 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&amp;java(二)
2006/10/09 PHP
Notice: Trying to get property of non-object problem(PHP)解决办法
2012/03/11 PHP
完美解决在ThinkPHP控制器中命名空间的问题
2017/05/05 PHP
javascript 获取图片颜色
2009/04/05 Javascript
Jquery cookie操作代码
2010/03/14 Javascript
jQuery 前的按键判断代码
2010/03/19 Javascript
jQuery实现回车键(Enter)切换文本框焦点的代码实例
2014/05/05 Javascript
Javascript中this的用法详解
2014/09/22 Javascript
JS简单操作select和dropdownlist实例
2014/11/26 Javascript
javascript表单验证和Window详解
2014/12/11 Javascript
简介JavaScript中toTimeString()方法的使用
2015/06/12 Javascript
jQuery Ajax和getJSON获取后台普通json数据和层级json数据用法分析
2016/06/08 Javascript
使用JavaScript实现alert的实例代码
2017/07/06 Javascript
BootStrap入门学习第一篇
2017/08/28 Javascript
详解使用Vue Router导航钩子与Vuex来实现后退状态保存
2017/09/11 Javascript
浅谈node的事件机制
2017/10/09 Javascript
Angular5.0 子组件通过service传递值给父组件的方法
2018/07/13 Javascript
jQuery实现的卷帘门滑入滑出效果【案例】
2019/02/18 jQuery
详解Vue2.5+迁移至Typescript指南
2019/08/01 Javascript
[14:36]2014 DOTA2国际邀请赛中国区预选赛5.21 Orenda VS NE
2014/05/22 DOTA
Python的网络编程库Gevent的安装及使用技巧
2016/06/24 Python
numpy.delete删除一列或多列的方法
2018/04/03 Python
Python3实现的字典、列表和json对象互转功能示例
2018/05/22 Python
解决新django中的path不能使用正则表达式的问题
2018/12/18 Python
详解python 爬取12306验证码
2019/05/10 Python
Python计算两个矩形重合面积代码实例
2019/09/16 Python
python实现俄罗斯方块游戏(改进版)
2020/03/13 Python
python 根据列表批量下载网易云音乐的免费音乐
2020/12/03 Python
来自Ocado的宠物商店:Fetch
2018/07/10 全球购物
社区服务活动总结
2014/05/07 职场文书
服务型党组织建设典型材料
2014/05/07 职场文书
文明美德伴我成长演讲稿
2014/05/12 职场文书
行风评议整改报告
2014/11/06 职场文书
学雷锋主题班会教案
2015/08/13 职场文书
2016年五一促销广告语
2016/01/28 职场文书
python 用递归实现通用爬虫解析器
2021/04/16 Python