1. Resty简介

微服务开发中服务间调用的主流方式有两种HTTP、RPC,HTTP相对来说比较简单。本文将使用 Resty 包来实现基于HTTP的微服务调用。
Resty 是一个简单的HTTP和REST客户端工具包,简单是指使用上非常简单。Resty在使用简单的基础上提供了非常强大的功能,涉及到HTTP客户端的方方面面,可以满足我们日常开发使用的大部分需求。
go get安装

  1. go get github.com/go-resty/resty/v2

使用Resty提交HTTP请求

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/go-resty/resty/v2"
  5. )
  6. func main() {
  7. client := resty.New()
  8. resp, err := client.R().Get("http://httpbin.org/get")
  9. fmt.Printf("\nError: %v", err)
  10. fmt.Printf("\nResponse Status Code: %v", resp.StatusCode())
  11. fmt.Printf("\nResponse Status: %v", resp.Status())
  12. fmt.Printf("\nResponse Time: %v", resp.Time())
  13. fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt())
  14. fmt.Printf("\nResponse Body: %v", resp)
  15. }

执行输出:

  1. Error: <nil>
  2. Response Status Code: 200
  3. Response Status: 200 OK
  4. Response Time: 752.38195ms
  5. Response Received At: 2020-12-18 16:04:16.211559068 +0800 CST m=+0.753544183
  6. Response Body: {
  7. "args": {},
  8. "headers": {
  9. "Accept-Encoding": "gzip",
  10. "Host": "httpbin.org",
  11. "User-Agent": "go-resty/2.3.0 (https://github.com/go-resty/resty)",
  12. "X-Amzn-Trace-Id": "Root=1-5fdc6280-1de9ea8f1558a5545c902521"
  13. },
  14. "origin": "212.129.130.147",
  15. "url": "http://httpbin.org/get"
  16. }

2. GET方法

  1. client := resty.New()
  2. resp, err := client.R().
  3. Get("https://httpbin.org/get")
  4. resp, err := client.R().
  5. SetQueryParams(map[string]string{
  6. "page_no": "1",
  7. "limit": "20",
  8. "sort":"name",
  9. "order": "asc",
  10. "random":strconv.FormatInt(time.Now().Unix(), 10),
  11. }).
  12. SetHeader("Accept", "application/json").
  13. SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
  14. Get("/search_result")
  15. resp, err := client.R().
  16. SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more").
  17. SetHeader("Accept", "application/json").
  18. SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
  19. Get("/show_product")
  20. resp, err := client.R().
  21. SetResult(AuthToken{}).
  22. ForceContentType("application/json").
  23. Get("v2/alpine/manifests/latest")

Resty 提供 SetQueryParams 方法设置请求的查询字符串,使用 SetQueryParams
方法我们可以动态的修改请求参数。

  • SetQueryString 也可以设置请求的查询字符串,如果参数中有变量的话,需要拼接字符串。
  • SetHeader 设置请求的HTTP头,以上代码设置了 Accept 属性。
  • SetAuthToken 设置授权信息,本质上还是设置HTTP头,以上例子中HTTP头会附加 Authorization: BearerBC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F 授权属性。
  • SetResult 设置返回值的类型,Resty自动解析json通过 resp.Result().(*AuthToken) 获取。

    3. POST方法

    1. client := resty.New()
    2. resp, err := client.R().
    3. SetBody(User{Username: "testuser", Password: "testpass"}).
    4. SetResult(&AuthSuccess{}).
    5. SetError(&AuthError{}).
    6. Post("https://myapp.com/login")
    7. resp, err := client.R().
    8. SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
    9. SetResult(&AuthSuccess{}).
    10. SetError(&AuthError{}).
    11. Post("https://myapp.com/login")
    12. resp, err := client.R().
    13. SetHeader("Content-Type", "application/json").
    14. SetBody(`{"username":"testuser", "password":"testpass"}`).
    15. SetResult(&AuthSuccess{}).
    16. Post("https://myapp.com/login")
    17. resp, err := client.R().
    18. SetHeader("Content-Type", "application/json").
    19. SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
    20. SetResult(&AuthSuccess{}).
    21. Post("https://myapp.com/login")
    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等错误时返回的数据类型。

    4. PUT方法

    1. client := resty.New()
    2. resp, err := client.R().
    3. SetBody(Article{
    4. Title: "go-resty",
    5. Content: "This is my article content, oh ya!",
    6. Author: "Jeevanandam M",
    7. Tags: []string{"article", "sample", "resty"},
    8. }).
    9. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
    10. SetError(&Error{}).
    11. Put("https://myapp.com/article/1234")
    PATCH,DELETE,HEAD,OPTIONS请求也是一样的, Resty 为我们提供了一致的方式发起不同请求。

    5. 高级应用

    5.1 代理

    使用 Resty 作为HTTP客户端使用的话,添加代理似乎是一个常见的需求。 Resty 提供了 SetProxy 方法为请求添加代理,还可以调用 RemoveProxy 移除代理。代码如下:
    1. client := resty.New()
    2. client.SetProxy("http://proxyserver:8888")
    3. client.RemoveProxy()

    5.2 重试

    1. client := resty.New()
    2. client.
    3. SetRetryCount(3).
    4. SetRetryWaitTime(5 * time.Second).
    5. SetRetryMaxWaitTime(20 * time.Second).
    6. SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) {
    7. return 0, errors.New("quota exceeded")
    8. })
    9. client.AddRetryCondition(
    10. func(r *resty.Response) (bool, error) {
    11. return r.StatusCode() == http.StatusTooManyRequests
    12. },
    13. )
    由于网络抖动带来的接口稳定性的问题 Resty 提供了重试功能来解决。以上代码我们可以看到 SetRetryCount 设置重试次数, SetRetryWaitTimeSetRetryMaxWaitTime 设置等待时间。 SetRetryAfter 是一个重试后的回调方法。除此之外还可以调用 AddRetryCondition 设置重试的条件。

    6. 中间件

    Resty 提供了和Gin类似的中间件特性。 OnBeforeRequestOnAfterResponse 回调方法,可以在请求之前和响应之后加入自定义逻辑。参数包含了 resty.Client 和当前请求的 resty.Request 对象。成功时返回 nil ,失败时返回 error 对象。
    1. client := resty.New()
    2. client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
    3. return nil
    4. })
    5. client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
    6. return nil
    7. })
    参考链接:
    https://github.com/go-resty/resty