侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

go语言之net/url包详解-url编码,组装示例代码

Go  /  管理员 发布于 3星期前   220

引言

在 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,例如 Parse、Path、Rawpath、string() 所有这些函数我们可以用于不同的目的。

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

运行结果:

> 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))
}

运行结果:

> 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())
}

运行代码:

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))
}

运行结果:

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())
}

运行代码:

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()
}

运行代码:

> 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()
}

处理结果

> 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()
}

运行结果:

> 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())
}

输出

> 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()
}

输出

> URL1 before modification is https://example.org
> URL2 before modification is https://example.org:8080
> URL2 Port number is 8080

转:

https://blog.51cto.com/yuzhou1su/5256521

  • 上一条:
    php语言实现图片文件md5修改示例代码
    下一条:
    如果VPN“翻墙”被全面取缔,“刚需”用户将何去何从?
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • go语言中Pat多路复用器路由功能示例代码(0个评论)
    • go语言中HttpRouter多路复用器路由功能示例代码(0个评论)
    • go语言中回收make()占用的内存代码示例(0个评论)
    • go语言中什么时候使用make或者new(0个评论)
    • go语言实现招商银行支付签名验证功能流程步骤(0个评论)
    • 近期文章
    • GnuPG(GPG)生成用于替代SSH密钥的子密钥:签名、加密、鉴权及SSH验证(0个评论)
    • GnuPG(GPG)密钥创建的流程步骤(0个评论)
    • Laravel 9.24版本发布(0个评论)
    • windows系统phpstudy环境中安装amqp拓展流程步骤(0个评论)
    • windows10+docker desktop使用docker compose编排多容器构建dnmp环境(0个评论)
    • windows10+docker desktop运行laravel项目报错:could not find driver...(0个评论)
    • windows10+docker desktop报错:docker: Error response from daemon: user declined directory sharing(0个评论)
    • go语言中Pat多路复用器路由功能示例代码(0个评论)
    • go语言中HttpRouter多路复用器路由功能示例代码(0个评论)
    • js中使用Push.js通知库将通知推送到浏览器(0个评论)
    • 近期评论
    • nkt 在

      阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 用了三分钟就被禁了,直接阿里云服务器22端口都禁了..
    • 熊丽 在

      安装docker + locust + boomer压测环境实现对接口的压测中评论 试试水..
    • 博主 在

      阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 @test  也可能是国内大环境所至,也是好事,督促你该研究学习新技术..
    • test 在

      阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 打了一次网页,然后再也打不开了。。是阿里云的缘故吗?..
    • 博主 在

      centos7中Meili Search搜索引擎安装流程步骤中评论 @鹿   执行以下命令看看你的2.27版本是否存在strin..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客