Go語言中最便捷的http請(qǐng)求包resty的使用詳解
go語言雖然自身就有net/http包,但是說實(shí)話用起來沒那么好用。resty包是go語言中一個(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語言中最便捷的http請(qǐng)求包resty的使用詳解的文章就介紹到這了,更多相關(guān)Go resty使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang標(biāo)準(zhǔn)庫unsafe源碼解讀
這篇文章主要為大家介紹了Golang標(biāo)準(zhǔn)庫unsafe源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08Go并發(fā)編程結(jié)構(gòu)體多字段原子操作示例詳解
這篇文章主要為大家介紹了Go并發(fā)編程結(jié)構(gòu)體多字段原子操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12golang常用加密解密算法總結(jié)(AES、DES、RSA、Sha1、MD5)
在項(xiàng)目開發(fā)過程中,當(dāng)操作一些用戶的隱私信息,本文主要主要介紹了golang常用加密解密算法總結(jié)(AES、DES、RSA、Sha1MD5),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04