
企業工商數據API用哪種?
Resty 提供了簡化的 API 來處理不同的 HTTP 請求方法,例如 GET、POST、PUT、PATCH、DELETE 等。
package main
import (
"fmt"
"github.com/go-resty/resty/v2"
)
func main() {
client := resty.New()
// 發送 POST 請求,附帶 JSON 數據
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody({"username": "test", "password": "1234"}
).
Post("https://demo.com/post")
if err != nil {
fmt.Printf("請求失敗: %v\n", err)
} else {
fmt.Printf("響應狀態碼: %d\n", resp.StatusCode())
fmt.Printf("響應正文: %s\n", resp.String())
}
}
可以使用 SetQueryParam 和 SetHeader 方法輕松地為請求添加查詢參數和請求頭。
設置查詢參數:
resp, err := client.R().
SetQueryParam("key1", "value1").
SetQueryParam("key2", "value2").
Get("https://demo.com/get")
設置請求頭:
resp, err := client.R().
SetHeader("Accept", "application/json").
Get("https://demo.com/get")
支持通過 SetBody 方法發送 JSON 或 XML 格式的數據。可以直接傳遞結構體、字符串、字節數組等。
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(map[string]string{"username": "test", "password": "1234"}).
Post("https://demo.com/post")
resp, err := client.R().
SetHeader("Content-Type", "application/xml").
SetBody(<user><name>test</name><password>1234</password></user>
).
Post("https://demo.com/post")
允許將響應的 JSON 數據自動解析到結構體中,使用 SetResult 或 SetError 方法來處理。
type User struct {
Name string json:"name"
Email string json:"email"
}
func main() {
client := resty.New()
user := &User{}
resp, err := client.R().
SetResult(user). // 自動解析 JSON 響應到 user 結構體
Get("https://demo.com/users/1")
if err != nil {
fmt.Printf("請求失敗: %v\n", err)
} else {
fmt.Printf("用戶名: %s\n", user.Name)
fmt.Printf("郵箱: %s\n", user.Email)
}
}
支持發送 x-www-form-urlencoded 或 multipart/form-data 表單數據。
resp, err := client.R().
SetFormData(map[string]string{
"username": "test",
"password": "1234",
}).
Post("https://demo.com/post")
可以通過 SetTimeout 方法為請求設置超時時間。
client := resty.New().
SetTimeout(5 * time.Second) // 請求超時設置為 5 秒
內置了重試機制,允許你為失敗的請求設置自動重試。
client := resty.New().
SetRetryCount(3). // 重試 3 次
SetRetryWaitTime(2 * time.Second) // 每次重試之間等待 2 秒
SetRetryMaxWaitTime(10 * time.Second) // 最大重試等待時間 10 秒
resp, err := client.R().
AddRetryCondition(
// 如果狀態碼為 500 則重試
func(r *resty.Response, err error) bool {
return r.StatusCode() == 500
},
).
Get("https://demo.com/status/500")
文件上傳:
resp, err := client.R().
SetFile("file", "example.txt").
Post("https://demo.com/post")
文件下載:
resp, err := client.R().
SetOutput("output.txt"). // 將響應內容保存到文件
Get("https://demo.com/get")
支持通過 SetCookie 方法為請求設置 Cookie,也可以通過 SetCookies 方法批量設置多個 Cookie。
設置單個 Cookie:
client.R().
SetCookie(&http.Cookie{
Name: "session_id",
Value: "abc123",
}).
Get("https://demo.com/cookies")
設置多個 Cookie:
client.R().
SetCookies([]*http.Cookie{
{Name: "cookie1", Value: "value1"},
{Name: "cookie2", Value: "value2"},
}).
Get("https://demo.com/cookies")
允許你通過 client.Set 方法為所有請求設置全局配置。例如,設置所有請求的默認頭部或超時時間。
client := resty.New().
SetHeader("Accept", "application/json") // 所有請求都帶有 Accept 頭
支持通過設置代理服務器來發送請求。
client := resty.New().
SetProxy("http://myproxy:8080")
內置了請求和響應的日志功能,允許你輕松調試 HTTP 請求。
client := resty.New().
SetDebug(true) // 啟用調試模式,打印所有請求和響應細節
允許通過 SetTransport 自定義 HTTP Transport,并支持為每個請求設置自定義的 Middleware。
client := resty.New().
SetTransport(&http.Transport{
Proxy: http.ProxyFromEnvironment,
})
支持鏈式調用,允許你以簡潔的方式進行多個設置操作。
client.R().
SetHeader("Accept", "application/json").
SetQueryParam("id", "123").
SetTimeout(5 * time.Second).
Get("https://demo.com/get")
允許在實際發送 HTTP 請求之前設置預定義的請求(Pre-request Hook)。
可以使用 OnBeforeRequest 鉤子在每個請求發送前執行一些操作,例如修改請求參數、設置頭部,或者做一些日志記錄。
client := resty.New().
OnBeforeRequest(func(c *resty.Client, r *resty.Request) error {
fmt.Println("請求即將發送: ", r.URL)
// 可以在這里動態設置請求頭或其他參數
r.SetHeader("Custom-Header", "MyValue")
return nil
})
resp, err := client.R().Get("https://demo.com/get")
類似于 OnBeforeRequest。
也支持 OnAfterResponse 鉤子,這個鉤子允許在請求響應后執行一些操作,比如記錄日志、修改響應內容等。
client := resty.New().
OnAfterResponse(func(c *resty.Client, r *resty.Response) error {
fmt.Printf("請求完成,狀態碼: %d\n", r.StatusCode())
// 可以在這里做一些后處理,例如檢查響應內容或記錄日志
return nil
})
resp, err := client.R().Get("https://demo.com/get")
在處理文件上傳時,支持通過多部分表單數據發送多個文件或數據段。
可以使用 SetFileReader 或 SetFormData 來上傳文件和表單字段。
fileReader, err := os.Open("example.txt")
if err != nil {
log.Fatal(err)
}
defer fileReader.Close()
resp, err := client.R().
SetFileReader("file", "example.txt", fileReader). // 使用文件讀取器
SetFormData(map[string]string{
"username": "test",
"password": "1234",
}).
Post("https://demo.com/post")
提供了強大的代理支持、基本認證、Bearer Token 和自定義 TLS 配置等功能。
使用代理:
client.SetProxy("http://proxy-server:8080")
使用認證和 Bearer Token:
client.R().SetBasicAuth("username", "password").Get("https://demo.com/basic-auth/user/passwd")
client.R().SetAuthToken("your-token").Get("https://demo.com/bearer")
自定義 TLS 配置:
client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
完全支持 Go 的 context.Context,可以通過 SetContext 來為請求設置上下文,以便在處理超時或取消請求時使用。
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
resp, err := client.R().
SetContext(ctx). // 使用 context 控制請求
Get("https://demo.com/delay/5") // 這個 URL 會延遲 5 秒返回,context 會在 2 秒后超時
允許通過 SetError 來指定一個用于處理錯誤的結構體。
當 HTTP 請求返回非 2xx 的狀態碼時,可以自動將響應體解析到指定的錯誤結構體中。
type ErrorResponse struct {
Message string json:"message"
}
errResponse := &ErrorResponse{}
resp, err := client.R().
SetError(errResponse). // 自動將錯誤響應解析為 ErrorResponse
Get("https://demo.com/status/400")
if err != nil {
fmt.Println("請求失敗:", errResponse.Message)
}
支持通過 SetPathParams 動態控制 URL 中的路徑參數,適合用于處理 RESTful API 的版本控制。
resp, err := client.R().
SetPathParams(map[string]string{
"version": "v1",
"id": "1234",
}).
Get("https://api.demo.com/{version}/users/{id}")
可以通過 Go 的 goroutine 與 channel 輕松處理并發請求,尤其適合需要同時向多個 API 發起請求的場景。
urls := []string{
"https://demo.com/get?1",
"https://demo.com/get?2",
"https://demo.com/get?3",
}
ch := make(chan *resty.Response)
for _, url := range urls {
go func(url string) {
resp, _ := client.R().Get(url)
ch <- resp
}(url)
}
for range urls {
resp := <-ch
fmt.Println("響應狀態碼:", resp.StatusCode())
}
可以設置全局的錯誤處理函數,確保每次請求在發生錯誤時都會調用這個函數。
通過 SetError 可以為每個請求配置錯誤處理。
client := resty.New().
OnError(func(req *resty.Request, err error) {
fmt.Printf("請求 %s 失敗: %v\n", req.URL, err)
})
resp, err := client.R().Get("https://demo.com/status/404")
工作中常用的功能,基本上都包括了…
如果你正在開發需要處理 HTTP 請求的應用,resty 是一個非常值得使用的工具。
在我封裝的框架中,HTTP 客戶端使用的正是 Resty。
文章轉自微信公眾號@程序員新亮