Resty 是一个简单的HTTP和REST客户端工具包,为什么不推荐使用net/http标准库呢,因为我在使用过程中发现请求https等协议还要自己写个跳过ssl证书认证,就很麻烦。而Resty可以直接连。
go get github.com/go-resty/resty/v2
使用Resty提交HTTP请求
package main
import (
"fmt"
"github.com/go-resty/resty/v2"
)
func main() {
client := resty.New()
resp, err := client.R().Get("http://httpbin.org/get")
fmt.Printf("\nError: %v", err)
fmt.Printf("\nResponse Status Code: %v", resp.StatusCode())
fmt.Printf("\nResponse Status: %v", resp.Status())
fmt.Printf("\nResponse Time: %v", resp.Time())
fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt())
fmt.Printf("\nResponse Body: %v", resp)
}
执行输出:
Error:
Response Status Code: 200
Response Status: 200 OK
Response Time: 752.38195ms
Response Received At: 2020-12-18 16:04:16.211559068 +0800 CST m=+0.753544183
Response Body: {
"args": {},
"headers": {
"Accept-Encoding": "gzip",
"Host": "httpbin.org",
"User-Agent": "go-resty/2.3.0 (https://github.com/go-resty/resty)",
"X-Amzn-Trace-Id": "Root=1-5fdc6280-1de9ea8f1558a5545c902521"
},
"origin": "212.129.130.147",
"url": "http://httpbin.org/get"
}
- GET方法
Resty 提供 SetQueryParams 方法设置请求的查询字符串,使用 SetQueryParams
方法我们可以动态的修改请求参数。
SetQueryString 也可以设置请求的查询字符串,如果参数中有变量的话,需要拼接字符串。
SetHeader 设置请求的HTTP头,以上代码设置了 Accept 属性。
SetAuthToken 设置授权信息,本质上还是设置HTTP头,以上例子中HTTP头会附加 Authorization: BearerBC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F 授权属性。
SetResult 设置返回值的类型,Resty自动解析json通过 resp.Result().(*AuthToken) 获取。
实例:
client := resty.New()
resp, err := client.R().
Get("https://httpbin.org/get")
resp, err := client.R().
SetQueryParams(map[string]string{
"page_no": "1",
"limit": "20",
"sort":"name",
"order": "asc",
"random":strconv.FormatInt(time.Now().Unix(), 10),
}).
SetHeader("Accept", "application/json").
SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
Get("/search_result")
resp, err := client.R().
SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
SetHeader("Accept", "application/json").
SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
Get("/show_product")
resp, err := client.R().
SetResult(AuthToken{}).
ForceContentType("application/json").
Get("v2/alpine/manifests/latest")
- POST方法
POST请求的代码和GET请求类似,只是最后调用了 Post 方法。POST请求可以附带BODY,代码中使用 SetBody 方法设置POST BODY。
SetBody 参数类型为结构体或 map[string]interface{} 时, Resty 自动附加HTTP头 Content-Type: application/json ,当参数为string或[]byte类型时由于很难推断内容的类型,所以需要手动设置 Content-Type 请求头。 SetBody 还支持其他类型的参数,例如上传文件时可能会用到的io.Reader。 SetError 设置HTTP状态码为4XX或5XX等错误时返回的数据类型。
client := resty.New()
resp, err := client.R().
SetBody(User{Username: "testuser", Password: "testpass"}).
SetResult(&AuthSuccess{}).
SetError(&AuthError{}).
Post("https://myapp.com/login")
resp, err := client.R().
SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
SetResult(&AuthSuccess{}).
SetError(&AuthError{}).
Post("https://myapp.com/login")
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(`{"username":"testuser", "password":"testpass"}`).
SetResult(&AuthSuccess{}).
Post("https://myapp.com/login")
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
SetResult(&AuthSuccess{}).
Post("https://myapp.com/login")