Go語(yǔ)言中最便捷的http請(qǐng)求包resty的使用詳解
go語(yǔ)言雖然自身就有net/http包,但是說實(shí)話用起來沒那么好用。resty包是go語(yǔ)言中一個(gè)非常受歡迎的http請(qǐng)求處理包,它的api非常簡(jiǎn)潔、屬于一看就懂的那種、對(duì)新手非常有友好。它支持鏈?zhǔn)秸{(diào)用、支持超時(shí)、重試機(jī)制,還支持中間件,可以在請(qǐng)求發(fā)送前,發(fā)送后做些操作,使用起來非常舒服。 今天我們一起來看下吧。
安裝
先來安裝下go get github.com/go-resty/resty/v2
一、一個(gè)簡(jiǎn)單的get
發(fā)一個(gè)get請(qǐng)求試試呢?
package main
import (
"fmt"
"github.com/go-resty/resty/v2"
)
func main() {
client := resty.New()
resp, err := client.R().
Get("https://www.baidu.com")
if err != nil {
fmt.Println("請(qǐng)求出錯(cuò):", err)
return
}
fmt.Println("狀態(tài)碼:", resp.StatusCode())
fmt.Println("響應(yīng)體:", resp.String())
fmt.Println("響應(yīng)頭:", resp.Header()) // 獲取全部header
fmt.Println("特定響應(yīng)頭:", resp.Header().Get("Content-Type")) // 獲取特定的header
// 狀態(tài)碼: 200
// 響應(yīng)體: xxx太多了省略掉...
// 響應(yīng)頭: map[Accept-Ranges:[bytes] Cache-Control:[no-cache] Connection:[keep-alive] Content-Length:[227] Content-Security-Policy:[frame-ancestors 'self' https://chat.baidu.com http://mirror-chat.baidu.com https://fj-chat.baidu.com https://hba-chat.baidu.com https://hbe-chat.baidu.com https://njjs-chat.baidu.com https://nj-chat.baidu.com https://hna-chat.baidu.com https://hnb-chat.baidu.com http://debug.baidu-int.com;] Content-Type:[text/html] Date:[Sun, 16 Mar 2025 09:43:18 GMT] P3p:[CP=" OTI DSP COR IVA OUR IND COM " CP=" OTI DSP COR IVA OUR IND COM "] Pragma:[no-cache] Server:[BWS/1.1] Set-Cookie:[BD_NOT_HTTPS=1; path=/; Max-Age=300 BIDUPSID=10846246655E82CCF356A792677D7EA8; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com PSTM=1742118198; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com BAIDUID=10846246655E82CC89D4B0052594BBBE:FG=1; max-age=31536000; expires=Mon, 16-Mar-26 09:43:18 GMT; domain=.baidu.com; path=/; version=1; comment=bd] Traceid:[1742118198045022490612843349543995319034] X-Ua-Compatible:[IE=Edge,chrome=1] X-Xss-Protection:[1;mode=block]]
// 特定響應(yīng)頭: text/html
}
使用起來非常簡(jiǎn)單,它支持鏈?zhǔn)秸{(diào)用,唯一需要注意的是**請(qǐng)求方式 + 路徑要放在最后——它返回響應(yīng)**。
二、帶查詢參數(shù)
resp, err := client.R().
SetQueryParam("postId", "1"). // 設(shè)置單個(gè)查詢參數(shù) 也是可以的
Get("https://jsonplaceholder.typicode.com/posts")
// resp, err := client.R().
// SetQueryParams(map[string]string{ // 設(shè)置多個(gè)查詢參數(shù)
// "postId": "1",
// }).
// Get("https://jsonplaceholder.typicode.com/posts")
它支持一次設(shè)置多個(gè)查詢參數(shù)SetQueryParams、和單個(gè)查詢參數(shù)SetQueryParam兩種方式方式。
三、設(shè)置請(qǐng)求頭、body
由于支持鏈?zhǔn)秸{(diào)用,設(shè)置請(qǐng)求頭也很方便
resp, err := client.R().
SetHeader("Content-Type", "application/json"). // 設(shè)置單個(gè)請(qǐng)求頭
SetBody(`{"title": "foo", "body": "bar", "userId": 1}`). // 字符串形式
Post("https://jsonplaceholder.typicode.com/posts")
resp, err := client.R().
SetBody(map[string]interface{}{ // 支持 map結(jié)構(gòu)
"title": "foo",
"body": "bar",
"userId": 1,
}).
SetHeaders(map[string]string{ // 設(shè)置多個(gè)請(qǐng)求頭
"Content-Type": "application/json",
}).
Post("https://jsonplaceholder.typicode.com/posts")
resp, err := client.R().
SetBody(Post{Title: "foo", Body: "bar", UserId: 1}). // 支持struct
SetHeaders(map[string]string{
"Content-Type": "application/json",
}).
Post("https://jsonplaceholder.typicode.com/posts")
// 從文件創(chuàng)建 io.Reader
file, err := os.Open("my_file.txt")
if err != nil {
// ... 錯(cuò)誤處理 ...
}
defer file.Close()
resp, err := client.R().
// 不設(shè)置也可以, resty會(huì)根據(jù)reader自動(dòng)推斷content-type
SetHeader("Content-Type", "application/octet-stream"). // 或者根據(jù)文件類型設(shè)置
SetBody(file). // 支持 io.Reader方式
Post("https://example.com/upload")
SetBody支持方式非常豐富json字符串、map、struct、[]byte、io.Reader- 設(shè)置請(qǐng)求頭和前面的設(shè)置查詢參數(shù)類似,同時(shí)支持單個(gè)、多個(gè)
復(fù)數(shù)s兩種方式。
四、設(shè)置表單數(shù)據(jù)
resp, err := client.R().
SetFormData(map[string]string{"title": "foo", "body": "bar", "userId": "1"}).
Post("https://jsonplaceholder.typicode.com/posts")
需要注意SetFormData參數(shù)只支持map[string]string類型。
五、處理響應(yīng)
// 請(qǐng)求
type postReq struct {
Title string `json:"title"`
Body string `json:"body"`
UserId int `json:"userId"`
}
// 響應(yīng)
type postRes struct {
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
UserId int `json:"userId"`
}
var pr postRes
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
SetResult(&pr). // 設(shè)置響應(yīng)后內(nèi)容
Post("https://jsonplaceholder.typicode.com/posts")
if err != nil {
fmt.Println("請(qǐng)求出錯(cuò):", err)
return
}
fmt.Println("請(qǐng)求成功了么?", resp.IsSuccess()) // 是否響應(yīng)成了
fmt.Printf("響應(yīng)結(jié)果:%#v\n", pr)
// 請(qǐng)求成功了么? true
// 響應(yīng)結(jié)果:main.postRes{ID:101, Title:"foo", Body:"bar", UserId:1}
IsSuccess判斷 響應(yīng)是否成SetResult支持把響應(yīng)結(jié)果映射到結(jié)構(gòu)體中
六、超時(shí)與重試
client := resty.New().
SetTimeout(5 * time.Second). // 設(shè)置超時(shí)時(shí)間
SetRetryCount(3). // 設(shè)置重試次數(shù)為 3
SetRetryWaitTime(1 * time.Second). // 設(shè)置重試間隔為 1 秒
SetRetryMaxWaitTime(5 * time.Second). //最大重試間隔
AddRetryCondition(
func(r *resty.Response, err error) bool {
return r.StatusCode() == http.StatusTooManyRequests // 429 錯(cuò)誤時(shí)重試
},
)
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
SetResult(&pr).
Post("https://jsonplaceholder.typicode.com/posts")
需要之一的是resty.New() 和 下面的 client.R()是不同的類,前者主要用于設(shè)置全局性相關(guān)的設(shè)置(比如:超時(shí)、重試等); 后者主要用于請(qǐng)求的發(fā)送相關(guān)設(shè)置;
七、調(diào)試模式
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
SetResult(&pr).
SetDebug(true). // 開啟調(diào)試模式
Post("https://jsonplaceholder.typicode.com/posts")
調(diào)試模式開啟,請(qǐng)求的所有參數(shù)、和響應(yīng)內(nèi)容都可以看到。
八、中間件
client := resty.New()
// 請(qǐng)求中間件
client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
fmt.Println("發(fā)送請(qǐng)求前:", req.URL)
// 可以修改請(qǐng)求, 比如 req.SetHeader("New-Header", "value")
return nil
})
// 響應(yīng)中間件
client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
fmt.Println("收到響應(yīng)后:", resp.Status())
return nil
})
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(postReq{Title: "foo", Body: "bar", UserId: 1}).
SetResult(&pr).
Post("https://jsonplaceholder.typicode.com/posts")
它也支持中間件,在發(fā)送請(qǐng)求前、請(qǐng)求后做些處理。
到此這篇關(guān)于Go語(yǔ)言中最便捷的http請(qǐng)求包resty的使用詳解的文章就介紹到這了,更多相關(guān)Go resty使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Go實(shí)現(xiàn)偽靜態(tài)URL重寫功能
在Web開發(fā)中,偽靜態(tài)URL已成為優(yōu)化網(wǎng)站架構(gòu)和提升SEO的常用技術(shù)手段,偽靜態(tài)URL是一種介于動(dòng)態(tài)URL和靜態(tài)URL之間的解決方案,本文給大家介紹了如何使用Go實(shí)現(xiàn)偽靜態(tài)URL重寫功能,需要的朋友可以參考下2024-08-08
Go?chassis云原生微服務(wù)開發(fā)框架應(yīng)用編程實(shí)戰(zhàn)
這篇文章主要為大家介紹了Go?chassis云原生微服務(wù)開發(fā)框架應(yīng)用編程實(shí)戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
解析go語(yǔ)言調(diào)用約定多返回值實(shí)現(xiàn)原理
這篇文章主要為大家介紹了解析go語(yǔ)言調(diào)用約定多返回值實(shí)現(xiàn)原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
GO 函數(shù)式選項(xiàng)模式(Functional Options Pattern)
Option模式支持傳遞多個(gè)參數(shù),并且在參數(shù)個(gè)數(shù)、類型發(fā)生變化時(shí)保持兼容性,任意順序傳遞參數(shù),下面給大家介紹GO 函數(shù)式選項(xiàng)模式(Functional Options Pattern)的相關(guān)知識(shí),感興趣的朋友一起看看吧2021-10-10
go?原子操作的方式及實(shí)現(xiàn)原理全面深入解析
這篇文章主要為大家介紹了go?原子操作的方式及實(shí)現(xiàn)原理深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
Golang設(shè)計(jì)模式之適配器模式介紹和代碼示例
適配器是一種結(jié)構(gòu)型設(shè)計(jì)模式, 它能使不兼容的對(duì)象能夠相互合作,可擔(dān)任兩個(gè)對(duì)象間的封裝器, 它會(huì)接收對(duì)于一個(gè)對(duì)象的調(diào)用, 并將其轉(zhuǎn)換為另一個(gè)對(duì)象可識(shí)別的格式和接口,本文將通過代碼示例詳細(xì)給大家介紹Golang的適配器模式2023-06-06

