Go語言中最便捷的http請求包resty的使用詳解
go語言雖然自身就有net/http包,但是說實話用起來沒那么好用。resty包是go語言中一個非常受歡迎的http請求處理包,它的api非常簡潔、屬于一看就懂的那種、對新手非常有友好。它支持鏈式調(diào)用、支持超時、重試機制,還支持中間件,可以在請求發(fā)送前,發(fā)送后做些操作,使用起來非常舒服。 今天我們一起來看下吧。
安裝
先來安裝下go get github.com/go-resty/resty/v2
一、一個簡單的get
發(fā)一個get請求試試呢?
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("請求出錯:", err) return } fmt.Println("狀態(tài)碼:", resp.StatusCode()) fmt.Println("響應體:", resp.String()) fmt.Println("響應頭:", resp.Header()) // 獲取全部header fmt.Println("特定響應頭:", resp.Header().Get("Content-Type")) // 獲取特定的header // 狀態(tài)碼: 200 // 響應體: xxx太多了省略掉... // 響應頭: 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]] // 特定響應頭: text/html }
使用起來非常簡單,它支持鏈式調(diào)用,唯一需要注意的是**請求方式 + 路徑
要放在最后——它返回響應**。
二、帶查詢參數(shù)
resp, err := client.R(). SetQueryParam("postId", "1"). // 設置單個查詢參數(shù) 也是可以的 Get("https://jsonplaceholder.typicode.com/posts") // resp, err := client.R(). // SetQueryParams(map[string]string{ // 設置多個查詢參數(shù) // "postId": "1", // }). // Get("https://jsonplaceholder.typicode.com/posts")
它支持一次設置多個查詢參數(shù)SetQueryParams
、和單個查詢參數(shù)SetQueryParam
兩種方式方式。
三、設置請求頭、body
由于支持鏈式調(diào)用,設置請求頭也很方便
resp, err := client.R(). SetHeader("Content-Type", "application/json"). // 設置單個請求頭 SetBody(`{"title": "foo", "body": "bar", "userId": 1}`). // 字符串形式 Post("https://jsonplaceholder.typicode.com/posts") resp, err := client.R(). SetBody(map[string]interface{}{ // 支持 map結構 "title": "foo", "body": "bar", "userId": 1, }). SetHeaders(map[string]string{ // 設置多個請求頭 "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 { // ... 錯誤處理 ... } defer file.Close() resp, err := client.R(). // 不設置也可以, resty會根據(jù)reader自動推斷content-type SetHeader("Content-Type", "application/octet-stream"). // 或者根據(jù)文件類型設置 SetBody(file). // 支持 io.Reader方式 Post("https://example.com/upload")
SetBody
支持方式非常豐富json字符串
、map
、struct
、[]byte
、io.Reader
- 設置請求頭和前面的設置查詢參數(shù)類似,同時支持單個、多個
復數(shù)s
兩種方式。
四、設置表單數(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
類型。
五、處理響應
// 請求 type postReq struct { Title string `json:"title"` Body string `json:"body"` UserId int `json:"userId"` } // 響應 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). // 設置響應后內(nèi)容 Post("https://jsonplaceholder.typicode.com/posts") if err != nil { fmt.Println("請求出錯:", err) return } fmt.Println("請求成功了么?", resp.IsSuccess()) // 是否響應成了 fmt.Printf("響應結果:%#v\n", pr) // 請求成功了么? true // 響應結果:main.postRes{ID:101, Title:"foo", Body:"bar", UserId:1}
IsSuccess
判斷 響應是否成SetResult
支持把響應結果映射到結構體中
六、超時與重試
client := resty.New(). SetTimeout(5 * time.Second). // 設置超時時間 SetRetryCount(3). // 設置重試次數(shù)為 3 SetRetryWaitTime(1 * time.Second). // 設置重試間隔為 1 秒 SetRetryMaxWaitTime(5 * time.Second). //最大重試間隔 AddRetryCondition( func(r *resty.Response, err error) bool { return r.StatusCode() == http.StatusTooManyRequests // 429 錯誤時重試 }, ) 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()
是不同的類,前者主要用于設置全局性相關的設置(比如:超時、重試等); 后者主要用于請求的發(fā)送相關設置;
七、調(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)試模式開啟,請求的所有參數(shù)、和響應內(nèi)容都可以看到。
八、中間件
client := resty.New() // 請求中間件 client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error { fmt.Println("發(fā)送請求前:", req.URL) // 可以修改請求, 比如 req.SetHeader("New-Header", "value") return nil }) // 響應中間件 client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error { fmt.Println("收到響應后:", 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ā)送請求前、請求后做些處理。
到此這篇關于Go語言中最便捷的http請求包resty的使用詳解的文章就介紹到這了,更多相關Go resty使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
golang常用加密解密算法總結(AES、DES、RSA、Sha1、MD5)
在項目開發(fā)過程中,當操作一些用戶的隱私信息,本文主要主要介紹了golang常用加密解密算法總結(AES、DES、RSA、Sha1MD5),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04