首页
📷在线壁纸
🎬娱乐天地
🔖友情链接
更多
📝留言板
Search
1
【javascript】JS-向当前url追加参数
2,345 阅读
2
【PHP】生成随机昵称
2,219 阅读
3
【PHP】判断一个字符串是否属于序列化后的数据
2,024 阅读
4
【css】html+css给文章页,做阅读全文
1,975 阅读
5
【PHP】 设计模式(23种)
1,910 阅读
📂默认分类
💓typecho
🏳️🌈代码改变世界
🍇 mysql
🍈 Winform
🍓 golang
🍉 设计模式
🥝 PHP
🍎 python
🍊 nginx
🍋 网络安全
🍍 javascript
🫑 database
🍭文艺范
🍏mac
AI
LLM
image
audio
yolo
3D
code
登录
Search
标签搜索
php
typecho
代码注释
redis
mysql
go
golang
nginx
thinkphp
docker
gin
linux
curl
html
mamp
算法
短网址
构造函数
webhook
代码片段
依然范儿特西
累计撰写
146
篇文章
累计收到
1
条评论
首页
栏目
📂默认分类
💓typecho
🏳️🌈代码改变世界
🍇 mysql
🍈 Winform
🍓 golang
🍉 设计模式
🥝 PHP
🍎 python
🍊 nginx
🍋 网络安全
🍍 javascript
🫑 database
🍭文艺范
🍏mac
AI
LLM
image
audio
yolo
3D
code
页面
📷在线壁纸
🎬娱乐天地
🔖友情链接
📝留言板
搜索到
1
篇与
的结果
2021-10-18
Golang 语言极简 HTTP 客户端 GoRequest
1 介绍GoRequest 是一个极简的 HTTP 客户端,作者灵感来源于 Node.js 库 SuperAgent。相比 Golang 标准库 net/http,GoRequest 使用起来更加简单。GoRequest 官方的口号是 “像机枪一样发送请求”。GoRequest 包含以下功能:支持 HTTP 请求方式:Get/Post/Put/Head/Delete/Patch/Options支持设置 header 请求头支持使用 JSON 字符串作为请求参数支持将多路请求的方式发送数据和文件支持通过代理发送请求支持为请求设置超时支持 TLS 客户端设置支持设置重定向策略支持为请求设置 cookieCookieJar - automatic in-memory cookiejar支持请求头设置基本身份认证安装方式:go get github.com/parnurzeal/gorequest2 HTTP请求方式Golang 发送一个简单的 Get 请求,使用 net/http 标准库和使用 GoRequst 库,两种发送 Get 请求的方式都比较简单。示例代码如下:标准库方式:resp, err := http.Get("http://example.com/")GoRequest 库方式:request := gorequest.New() resp, body, errs := request.Get("http://example.com/").End()或(该 GoRequest 方式无法复用对象)resp, body, errs := gorequest.New().Get("http://example.com/").End()阅读上面这两段代码,我们可以发现,使用标准库的方式发送 Get 请求,甚至比使用 GoRequest 库的方式发送 Get 请求更加简单。但是,当我们需求稍作修改,比如我们需要为 Get 请求,设置 header 头和设置重定向策略。我们再来看一下分别使用标准库和 GoRequest 库两种实现方式。标准库方式:client := &http.Client{ CheckRedirect: redirectPolicyFunc, } req, err := http.NewRequest("GET", "http://example.com", nil) req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req)GoRequest 库方式(其它 HTTP 请求方式与 Get 使用方式相同):request := gorequest.New() resp, body, errs := request.Get("http://example.com"). RedirectPolicy(redirectPolicyFunc). Set("If-None-Match", `W/"wyzzy"`). End()阅读上面两段代码,很容易发现使用 GoRequest 方式使实现更加简单。使用标准库方式,首先需要创建一个 Client,然后使用不同的命令设置 header 头等操作,这仅仅是为了实现一个 HTTP 请求。而使用 GoRequest 方式,仅需链式调用两个方法即可轻松实现。3 JSON 格式请求参数在 Golang 语言中,如果使用标准库 net/http 发送请求参数为 JSON 格式的 POST 请求,首先需要先将 map 或 struct 类型的数据,使用标准库 encoding/json 的 Marshal 方法,将数据转换为 JSON 格式的数据,并且设置 header 头参数 Content-Type 的值为 application/json,然后创建一个 Client,最终你的代码变得越来越长,越来越难维护。标准库方式:m := map[string]interface{}{ "name": "backy", "species": "dog", } mJson, _ := json.Marshal(m) contentReader := bytes.NewReader(mJson) req, _ := http.NewRequest("POST", "http://example.com", contentReader) req.Header.Set("Content-Type", "application/json") req.Header.Set("Notes","GoRequest is coming!") client := &http.Client{} resp, _ := client.Do(req)如果使用 GoRequest 库发送请求参数为 JSON 格式的 POST 请求,因为它默认支持 JSON 格式的请求参数,所以它只需要一行代码就可以实现。GoRequest 库方式:request := gorequest.New() resp, body, errs := request.Post("http://example.com"). Set("Notes","gorequst is coming!"). Send(`{"name":"backy", "species":"dog"}`). End()4支持回调函数 CallbackGoRequest 库还支持回调函数,你可以根据自己的项目需求灵活使用它,回调函数示例代码如下:func printStatus(resp gorequest.Response, body string, errs []error){ fmt.Println(resp.Status) } gorequest.New().Get("http://example.com").End(printStatus)5 请求控制在 Golang 项目开发中,有时我们可能需要对请求做一些额外控制,比如超时处理,重试请求 N 次,重定向处理等。GoRequest 库都可以为我们提供简单的实现方式。超时处理:request := gorequest.New().Timeout(2*time.Millisecond) resp, body, errs:= request.Get("http://example.com").End()需要注意的是,Timeout 是将 Dial 连接和 IO 读写的耗时总和,与时间参数作比较。重试请求:request := gorequest.New() resp, body, errs := request.Get("http://example.com/"). Retry(3, 5 * time.Second, http.StatusBadRequest, http.StatusInternalServerError). End()阅读上面这段代码,它的含义是当服务器返回结果是 http.StatusBadRequest 或 http.StatusInternalServerError 时,会每隔 5 秒重试请求一次,共重试 3 次。重定向处理:request := gorequest.New() resp, body, errs := request.Get("http://example.com/"). RedirectPolicy(func(req Request, via []*Request) error { if req.URL.Scheme != "https" { return http.ErrUseLastResponse } }). End() 阅读上面这段代码,它的含义是将 http 请求重定向为 https 请求。6 返回结果处理方式朋友们可能已经发现,以上示例代码都是以 End 结束,End 的含义是返回结果是字符串类型,如果我们希望返回结果是其他类型,比如字节类型和结构体类型,可以将 End 分别替换为 EndBytes 和 EndStruct。EndBytes 格式:resp, bodyBytes, errs := gorequest.New().Get("http://example.com/").EndBytes()EndStruct 格式:heyYou struct { Hey string `json:"hey"` } var heyYou heyYou resp, _, errs := gorequest.New().Get("http://example.com/").EndStruct(&heyYou)7 总结本文我们介绍 Golang 语言的极简 HTTP 客户端 GoRequest 以及它的使用方法。它比标准库 net/http 使用方式简单,当我们项目开发中需要使用 HTTP 方式调用接口时,强烈推荐使用 GoRequest 库。GoRequest 底层在大多数用例中是基于 http.Client 实现的,所以通过一次调用 gorequest.New() 得到的对象,应尽可能多次使用。GoRequest 除了上面介绍的 JSON 参数,它还支持 Struct 和 File,感兴趣的读者可以查阅官方文档了解相关内容。https://github.com/parnurzeal/gorequest
2021年10月18日
261 阅读
0 评论
1 点赞