Resty 中文文档

Go 的简单的 HTTP 和 REST 客户端库 (灵感来源于 Ruby 的 rest-client)

Features 详细描述了 Resty 的功能

Build Status Code Coverage Go Report Card Release Version GoDoc License

Resty Communication Channels

Chat on Gitter - Resty Community Twitter @go_resty

News

  • v2.0.0 released and tagged on Jul 16, 2019.
  • v1.12.0 released and tagged on Feb 27, 2019.
  • v1.0 released and tagged on Sep 25, 2017. - Resty’s first version was released on Sep 15, 2015 then it grew gradually as a very handy and helpful library. Its been a two years since first release. I’m very thankful to Resty users and its contributors.

Features

  • GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, etc.
  • Simple and chainable methods for settings and request
  • Request Body can be string, []byte, struct, map, slice and io.Reader too
    • Auto detects Content-Type
    • Buffer less processing for io.Reader
  • Response object gives you more possibility
    • Access as []byte array - response.Body() OR Access as string - response.String()
    • Know your response.Time() and when we response.ReceivedAt()
  • Automatic marshal and unmarshal for JSON and XML content type
  • Easy to upload one or more file(s) via multipart/form-data
    • Auto detects file content type
  • Request URL Path Params (aka URI Params)
  • Backoff Retry Mechanism with retry condition function reference
  • Resty client HTTP & REST Request and Response middlewares
  • Request.SetContext supported
  • Authorization option of BasicAuth and Bearer token
  • Set request ContentLength value for all request or particular request
  • Custom Root Certificates and Client Certificates
  • Download/Save HTTP response directly into File, like curl -o flag. See SetOutputDirectory & SetOutput.
  • Cookies for your request and CookieJar support
  • SRV Record based request instead of Host URL
  • Client settings like Timeout, RedirectPolicy, Proxy, TLSClientConfig, Transport, etc.
  • Optionally allows GET request with payload, see SetAllowGetMethodPayload
  • Supports registering external JSON library into resty, see how to use
  • Exposes Response reader without reading response (no auto-unmarshaling) if need be, see how to use
  • Option to specify expected Content-Type when response Content-Type header missing. Refer to #92
  • Resty design
    • Have client level settings & options and also override at Request level if you want to
    • Request and Response middlewares
    • Create Multiple clients if you want to resty.New()
    • Supports http.RoundTripper implementation, see SetTransport
    • goroutine concurrent safe
    • Resty Client trace, see Client.EnableTrace and Request.EnableTrace
    • Debug mode - clean and informative logging presentation
    • Gzip - Go does it automatically also resty has fallback handling too
    • Works fine with HTTP/2 and HTTP/1.1
  • Bazel support
  • Easily mock Resty for testing, for e.g.
  • Well tested client library

Included Batteries

  • 重定向策略 - 如何使用查看 这里
    • NoRedirectPolicy
    • FlexibleRedirectPolicy
    • DomainCheckRedirectPolicy
    • 等等。 更多信息
  • 重试机制,如何使用查看 这里
    • Backoff Retry
    • Conditional Retry
  • SRV Record based request instead of Host URL how to use
  • etc (upcoming - throw your idea’s here).

Supported Go Versions

最初,Resty 从 v1.10.0 版本开始支持go modules

使用 Resty v2 和更高的版本, 它完全包含 go modules 包版本.。

它需要一个能够理解 /vN 后缀导入的 Go 版本:

  • 1.9.7+
  • 1.10.3+
  • 1.11+

It might be beneficial for your project :smile:

Resty 的作者还为 Go 发布了以下项目。

  • aah framework - 一个安全、灵活、快速的 Go web 框架。
  • THUMBAI - Go Mod 仓库, Go Vanity 服务和简单的代理服务器。
  • go-model - 健壮的,易于使用的 Go struct 模型映射器和工具方法。

Installation

  1. # Go Modules
  2. require github.com/go-resty/resty/v2 v2.0.0

Usage

下面的示例会帮助你熟悉 resty 库。

  1. // 导入 resty
  2. import "github.com/go-resty/resty/v2"

Simple GET

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. resp, err := client.R().
  4. EnableTrace().
  5. Get("https://httpbin.org/get")
  6. // Explore response object
  7. fmt.Println("Response Info:")
  8. fmt.Println("Error :", err)
  9. fmt.Println("Status Code:", resp.StatusCode())
  10. fmt.Println("Status :", resp.Status())
  11. fmt.Println("Time :", resp.Time())
  12. fmt.Println("Received At:", resp.ReceivedAt())
  13. fmt.Println("Body :\n", resp)
  14. fmt.Println()
  15. // Explore trace info
  16. fmt.Println("Request Trace Info:")
  17. ti := resp.Request.TraceInfo()
  18. fmt.Println("DNSLookup :", ti.DNSLookup)
  19. fmt.Println("ConnTime :", ti.ConnTime)
  20. fmt.Println("TLSHandshake :", ti.TLSHandshake)
  21. fmt.Println("ServerTime :", ti.ServerTime)
  22. fmt.Println("ResponseTime :", ti.ResponseTime)
  23. fmt.Println("TotalTime :", ti.TotalTime)
  24. fmt.Println("IsConnReused :", ti.IsConnReused)
  25. fmt.Println("IsConnWasIdle:", ti.IsConnWasIdle)
  26. fmt.Println("ConnIdleTime :", ti.ConnIdleTime)
  27. /* Output
  28. Response Info:
  29. Error : <nil>
  30. Status Code: 200
  31. Status : 200 OK
  32. Time : 465.301137ms
  33. Received At: 2019-03-10 01:52:33.772456 -0800 PST m=+0.466672260
  34. Body :
  35. {
  36. "args": {},
  37. "headers": {
  38. "Accept-Encoding": "gzip",
  39. "Host": "httpbin.org",
  40. "User-Agent": "go-resty/2.0.0-rc.1 (https://github.com/go-resty/resty)"
  41. },
  42. "origin": "0.0.0.0",
  43. "url": "https://httpbin.org/get"
  44. }
  45. Request Trace Info:
  46. DNSLookup : 2.21124ms
  47. ConnTime : 393.875795ms
  48. TLSHandshake : 319.313546ms
  49. ServerTime : 71.109256ms
  50. ResponseTime : 94.466µs
  51. TotalTime : 465.301137ms
  52. IsConnReused : false
  53. IsConnWasIdle: false
  54. ConnIdleTime : 0s
  55. */

Enhanced GET

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. resp, err := client.R().
  4. SetQueryParams(map[string]string{
  5. "page_no": "1",
  6. "limit": "20",
  7. "sort":"name",
  8. "order": "asc",
  9. "random":strconv.FormatInt(time.Now().Unix(), 10),
  10. }).
  11. SetHeader("Accept", "application/json").
  12. SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F").
  13. Get("/search_result")
  14. // 使用 Request.SetQueryString 方法示例
  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")

Various POST method combinations

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // POST JSON string
  4. // 不需要设置 content type, 如果你有 client level 的设置
  5. resp, err := client.R().
  6. SetHeader("Content-Type", "application/json").
  7. SetBody(`{"username":"testuser", "password":"testpass"}`).
  8. SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
  9. Post("https://myapp.com/login")
  10. // POST []byte array
  11. // 不需要设置 content type, 如果你有 client level 的设置
  12. resp, err := client.R().
  13. SetHeader("Content-Type", "application/json").
  14. SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
  15. SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
  16. Post("https://myapp.com/login")
  17. // POST Struct, 默认为 JSON content type。不需要设置
  18. resp, err := client.R().
  19. SetBody(User{Username: "testuser", Password: "testpass"}).
  20. SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
  21. SetError(&AuthError{}). // or SetError(AuthError{}).
  22. Post("https://myapp.com/login")
  23. // POST Map, 默认为 JSON content type。不需要设置
  24. resp, err := client.R().
  25. SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
  26. SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
  27. SetError(&AuthError{}). // or SetError(AuthError{}).
  28. Post("https://myapp.com/login")
  29. // POST of raw bytes for file upload. For example: upload file to Dropbox
  30. fileBytes, _ := ioutil.ReadFile("/Users/jeeva/mydocument.pdf")
  31. // 这里我们没有设置 ,因为 go-resty 会自动为你检测 content-type
  32. resp, err := client.R().
  33. SetBody(fileBytes).
  34. SetContentLength(true). // Dropbox expects this value
  35. SetAuthToken("<your-auth-token>").
  36. SetError(&DropboxError{}). // or SetError(DropboxError{}).
  37. Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // for upload Dropbox supports PUT too
  38. // 注意: 如果 content-type 的 header, resty 检测请求 body/payload 的 Content-Type.
  39. // * 对于 struct 和 map 数据类型默认为 'application/json'
  40. // * Fallback is plain text content type

Sample PUT

你可以像使用 POST 一样,使用各种组合调用 PUT 方法。

  1. // 注意: 这是 PUT 方法使用的一个示例,更多的组合请参考 POST
  2. // 创建一个 Resty Client
  3. client := resty.New()
  4. // Request goes as JSON content type
  5. // 不需要设置 auth token, error, 如果你有 client level 的设置
  6. resp, err := client.R().
  7. SetBody(Article{
  8. Title: "go-resty",
  9. Content: "This is my article content, oh ya!",
  10. Author: "Jeevanandam M",
  11. Tags: []string{"article", "sample", "resty"},
  12. }).
  13. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
  14. SetError(&Error{}). // or SetError(Error{}).
  15. Put("https://myapp.com/article/1234")

Sample PATCH

你可以像使用 POST 一样,使用各种组合调用 PATCH 方法。

  1. // 注意: 这是 PATCH 方法使用的一个示例,更多的组合请参考 POST
  2. // 创建一个 Resty Client
  3. client := resty.New()
  4. // Request goes as JSON content type
  5. // 不需要设置 auth token, error, 如果你有 client level 的设置
  6. resp, err := client.R().
  7. SetBody(Article{
  8. Tags: []string{"new tag1", "new tag2"},
  9. }).
  10. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
  11. SetError(&Error{}). // or SetError(Error{}).
  12. Patch("https://myapp.com/articles/1234")

Sample DELETE, HEAD, OPTIONS

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // DELETE a article
  4. // 不需要设置 auth token, error, 如果你有 client level 的设置
  5. resp, err := client.R().
  6. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
  7. SetError(&Error{}). // or SetError(Error{}).
  8. Delete("https://myapp.com/articles/1234")
  9. // DELETE a articles with payload/body as a JSON string
  10. // 不需要设置 auth token, error, 如果你有 client level 的设置
  11. resp, err := client.R().
  12. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
  13. SetError(&Error{}). // or SetError(Error{}).
  14. SetHeader("Content-Type", "application/json").
  15. SetBody(`{article_ids: [1002, 1006, 1007, 87683, 45432] }`).
  16. Delete("https://myapp.com/articles")
  17. // HEAD of resource
  18. // 不需要设置 auth token, error, 如果你有 client level 的设置
  19. resp, err := client.R().
  20. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
  21. Head("https://myapp.com/videos/hi-res-video")
  22. // OPTIONS of resource
  23. // 不需要设置 auth token, error, 如果你有 client level 的设置
  24. resp, err := client.R().
  25. SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
  26. Options("https://myapp.com/servers/nyc-dc-01")

Multipart File(s) upload

Using io.Reader

  1. profileImgBytes, _ := ioutil.ReadFile("/Users/jeeva/test-img.png")
  2. notesBytes, _ := ioutil.ReadFile("/Users/jeeva/text-file.txt")
  3. // 创建一个 Resty Client
  4. client := resty.New()
  5. resp, err := client.R().
  6. SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)).
  7. SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)).
  8. SetFormData(map[string]string{
  9. "first_name": "Jeevanandam",
  10. "last_name": "M",
  11. }).
  12. Post("http://myapp.com/upload")

Using File directly from Path

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 上传一个文件
  4. resp, err := client.R().
  5. SetFile("profile_img", "/Users/jeeva/test-img.png").
  6. Post("http://myapp.com/upload")
  7. // 上传多个文件
  8. resp, err := client.R().
  9. SetFiles(map[string]string{
  10. "profile_img": "/Users/jeeva/test-img.png",
  11. "notes": "/Users/jeeva/text-file.txt",
  12. }).
  13. Post("http://myapp.com/upload")
  14. // Multipart of form fields and files
  15. resp, err := client.R().
  16. SetFiles(map[string]string{
  17. "profile_img": "/Users/jeeva/test-img.png",
  18. "notes": "/Users/jeeva/text-file.txt",
  19. }).
  20. SetFormData(map[string]string{
  21. "first_name": "Jeevanandam",
  22. "last_name": "M",
  23. "zip_code": "00001",
  24. "city": "my city",
  25. "access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD",
  26. }).
  27. Post("http://myapp.com/profile")

Sample Form submission

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 以 POST 作为一个简单的例子
  4. // User Login
  5. resp, err := client.R().
  6. SetFormData(map[string]string{
  7. "username": "jeeva",
  8. "password": "mypass",
  9. }).
  10. Post("http://myapp.com/login")
  11. // Followed by profile update
  12. resp, err := client.R().
  13. SetFormData(map[string]string{
  14. "first_name": "Jeevanandam",
  15. "last_name": "M",
  16. "zip_code": "00001",
  17. "city": "new city update",
  18. }).
  19. Post("http://myapp.com/profile")
  20. // Multi value form data
  21. criteria := url.Values{
  22. "search_criteria": []string{"book", "glass", "pencil"},
  23. }
  24. resp, err := client.R().
  25. SetFormDataFromValues(criteria).
  26. Post("http://myapp.com/search")

Save HTTP Response into File

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 设置要输出的目录路径, 如果目录不存在,go-resty 会创建
  4. // 这是一个可选项, 如果你计划在 `Request.SetOutput` 中使用绝对路径,可以一起使用
  5. client.SetOutputDirectory("/Users/jeeva/Downloads")
  6. // HTTP 响应保存到文件中, 类似于 curl 的 -o 标志
  7. _, err := client.R().
  8. SetOutput("plugin/ReplyWithHeader-v5.1-beta.zip").
  9. Get("http://bit.ly/1LouEKr")
  10. // 或者使用绝对路径
  11. // 注意: 输出目录路径不能用于绝对路径
  12. _, err := client.R().
  13. SetOutput("/MyDownloads/plugin/ReplyWithHeader-v5.1-beta.zip").
  14. Get("http://bit.ly/1LouEKr")

Request URL Path Params

Resty 提供了易于使用的动态请求 URL 路径参数。可以在 client 和 request level 设置参数。 request level 设置的参数会覆盖 client level 的设置的相同参数的值。

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. client.R().SetPathParams(map[string]string{
  4. "userId": "sample@sample.com",
  5. "subAccountId": "100002",
  6. }).
  7. Get("/v1/users/{userId}/{subAccountId}/details")
  8. // Result:
  9. // 组成的 URL - /v1/users/sample@sample.com/100002/details

Request and Response Middleware

Resty 提供了处理请求和响应的中间件功能。它比回调函数更灵活。

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 注册 Request 中间件
  4. client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
  5. // 现在你可以访问当前 Client 和 Request 对象
  6. // 根据你的需要操作它们
  7. return nil // 成功返回 nil,否则返回 error
  8. })
  9. // 注册 Response 中间件
  10. client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
  11. // Now you have access to Client and current Response object
  12. // manipulate it as per your need
  13. return nil // if its success otherwise return error
  14. })

Redirect Policy

Resty 提供了一些可以使用重定向策略的选项,而且它支持同时使用多个策略。

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 设置 Client 的 Redirect Policy. 根据需要创建一个
  4. client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(15))
  5. // 想要多个策略,如重定向计数,域名检查等
  6. client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20),
  7. resty.DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))
Custom Redirect Policy

实现 RedirectPolicy 接口并且使用 resty client 注册它. 更多内容查看 redirect.go

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 在 resty.SetRedirectPolicy 使用原始函数
  4. client.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
  5. // 这里实现你的逻辑
  6. // 继续重定向返回 nil ,否则返回 error 以停止/阻止重定向
  7. return nil
  8. }))
  9. //---------------------------------------------------
  10. // 使用 struct 创建更多的灵活的 redirect policy
  11. type CustomRedirectPolicy struct {
  12. // variables goes here
  13. }
  14. func (c *CustomRedirectPolicy) Apply(req *http.Request, via []*http.Request) error {
  15. // 这里实现你的逻辑
  16. // 继续重定向返回 nil ,否则返回 error 以停止/阻止重定向
  17. return nil
  18. }
  19. // 在 resty 里注册
  20. client.SetRedirectPolicy(CustomRedirectPolicy{/* initialize variables */})

Custom Root Certificates and Client Certificates

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 自定义的 Root 证书, 只需要提供 .pem 文件
  4. // 你可以添加一个或多个 root 证书
  5. client.SetRootCertificate("/path/to/root/pemFile1.pem")
  6. client.SetRootCertificate("/path/to/root/pemFile2.pem")
  7. // ... and so on!
  8. // 添加 Client 证书, 你可以添加一个或多个证书
  9. // 创建 certificate 对象的示例
  10. // 从一对文件中解析 public/private key. 这些文件必须包含P EM 编码的数据。
  11. cert1, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
  12. if err != nil {
  13. log.Fatalf("ERROR client certificate: %s", err)
  14. }
  15. // ...
  16. // 添加一个或多个证书
  17. client.SetCertificates(cert1, cert2, cert3)

Proxy Settings - Client as well as at Request Level

默认情况下 Go 支持从环境变量 HTTP_PROXY 获取代理。Resty 提供了 SetProxy & RemoveProxy, 根据你的需要来选择代理。

Client Level Proxy 应用于所有请求的设置

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 设置一个 Proxy URL 和 Port
  4. client.SetProxy("http://proxyserver:8888")
  5. // 移除 proxy 设置
  6. client.RemoveProxy()

Retries

Resty 使用 backoff 来增加每次尝试后的重试间隔。

使用示例:

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 每个 client 配置重试
  4. client.
  5. // 将重试计数设置为 非零 以启用重试
  6. SetRetryCount(3).
  7. // 你可以覆盖初始的重试等待时间。
  8. // 默认 100 毫秒.
  9. SetRetryWaitTime(5 * time.Second).
  10. // MaxWaitTime 也可以被覆盖.
  11. // 默认是 2 秒.
  12. SetRetryMaxWaitTime(20 * time.Second).
  13. // SetRetryAfter 设置回调函数来计算重试之间的等待时间。
  14. // Default (nil) implies exponential backoff with jitter
  15. SetRetryAfter(func(client *Client, resp *Response) (time.Duration, error) {
  16. return 0, errors.New("quota exceeded")
  17. })

上面的设置,当请求返回非 nil 的 error 时,resty 会重试请求 3 次。

可以选择为 client 提供自定义的重试条件:

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. client.AddRetryCondition(
  4. // RetryConditionFunc type is for retry condition function
  5. // input: non-nil Response OR request execution error
  6. func(r *resty.Response, err error) bool {
  7. return r.StatusCode() == http.StatusTooManyRequests
  8. },
  9. )

上面的例子,如果请求以 429 Too Many requests 状态码结束,resty 会重试请求。

可以添加多个重试条件。

还可以使用 resty.Backoff(...) 获得任意重试场景的实现。Reference

Allow GET request with Payload

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 允许带有 Payload 的 GET 请求。默认是 disabled 的。
  4. client.SetAllowGetMethodPayload(true)

Wanna Multiple Clients

  1. // Here you go!
  2. // Client 1
  3. client1 := resty.New()
  4. client1.R().Get("http://httpbin.org")
  5. // ...
  6. // Client 2
  7. client2 := resty.New()
  8. client2.R().Head("http://httpbin.org")
  9. // ...
  10. // Bend it as per your need!!!

Remaining Client Settings & its Options

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // Client level 的唯一设置
  4. //--------------------------------
  5. // 启用 debug 模式
  6. client.SetDebug(true)
  7. // 设置 Client TLSClientConfig
  8. // 设置自定义的 root-certificate. 参考: http://golang.org/pkg/crypto/tls/#example_Dial
  9. client.SetTLSClientConfig(&tls.Config{ RootCAs: roots })
  10. // 或者禁用安全检查 (https)
  11. client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })
  12. // 根据需要设置 client 超时
  13. client.SetTimeout(1 * time.Minute)
  14. // 如果你想,你可以在 request level 覆盖下面的所有的设置和选项
  15. //--------------------------------------------------------------------------------
  16. // 设置所有请求的 Host URL。就可以在所有请求中使用相对路径
  17. client.SetHostURL("http://httpbin.org")
  18. // 设置所有请求的 Headers
  19. client.SetHeader("Accept", "application/json")
  20. client.SetHeaders(map[string]string{
  21. "Content-Type": "application/json",
  22. "User-Agent": "My custom User Agent String",
  23. })
  24. // 设置所有请求的 Cookies
  25. client.SetCookie(&http.Cookie{
  26. Name:"go-resty",
  27. Value:"This is cookie value",
  28. Path: "/",
  29. Domain: "sample.com",
  30. MaxAge: 36000,
  31. HttpOnly: true,
  32. Secure: false,
  33. })
  34. client.SetCookies(cookies)
  35. // 设置所有请求的 URL query parameters
  36. client.SetQueryParam("user_id", "00001")
  37. client.SetQueryParams(map[string]string{ // sample of those who use this manner
  38. "api_key": "api-key-here",
  39. "api_secert": "api-secert",
  40. })
  41. client.R().SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")
  42. // 设置所有请求的 Form data. 通常和 POST and PUT 一起
  43. client.SetFormData(map[string]string{
  44. "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
  45. })
  46. // 设置所有请求的 Basic Auth
  47. client.SetBasicAuth("myuser", "mypass")
  48. // 设置所有请求的 Bearer Auth Token
  49. client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
  50. // 启用所有请求的 Content length value
  51. client.SetContentLength(true)
  52. // 为 JSON/XML 请求注册全局的 Error 对象结构体
  53. client.SetError(&Error{}) // or resty.SetError(Error{})

Unix Socket

  1. unixSocket := "/var/run/my_socket.sock"
  2. // 创建一个 Go 原生的 http.Transport ,这样可以在 resty 中设置它.
  3. transport := http.Transport{
  4. Dial: func(_, _ string) (net.Conn, error) {
  5. return net.Dial("unix", unixSocket)
  6. },
  7. }
  8. // 创建一个 Resty Client
  9. client := resty.New()
  10. // 设置之前创建的 transport, 将通信 scheme 设置为套接字,并将 unixSocket 设置为 HostURL。
  11. client.SetTransport(&transport).SetScheme("http").SetHostURL(unixSocket)
  12. // 不需要在请求上写主机的 URL,只需要路径。
  13. client.R().Get("/index.html")

Bazel support

Resty 可以通过 Bazel 构建、测试和依赖 . 例如,运行所有 test:

  1. bazel test :go_default_test

Mocking http requests using httpmock library

为了在测试应用程序时模拟 http 请求,可以使用 httpmock 库。 当使用默认 resty client, 要把 client 传递给库,像下面这样:

  1. // 创建一个 Resty Client
  2. client := resty.New()
  3. // 获取底层的 HTTP Client,并设置为 Mock
  4. httpmock.ActivateNonDefault(client.GetClient())

使用 ginko 模拟 resty http 请求的更详细示例在 这里

Versioning

Resty releases versions according to Semantic Versioning

  • Resty v2 does not use gopkg.in service for library versioning.
  • Resty fully adapted to go mod capabilities since v1.10.0 release.
  • Resty v1 series was using gopkg.in to provide versioning. gopkg.in/resty.vX points to appropriate tagged versions; X denotes version series number and it’s a stable release for production use. For e.g. gopkg.in/resty.v0.
  • Development takes place at the master branch. Although the code in master should always compile and test successfully, it might break API’s. I aim to maintain backwards compatibility, but sometimes API’s and behavior might be changed to fix a bug.

Contribution

I would welcome your contribution! If you find any improvement or issue you want to fix, feel free to send a pull request, I like pull requests that include test cases for fix/enhancement. I have done my best to bring pretty good code coverage. Feel free to write tests.

BTW, I’d like to know what you think about Resty. Kindly open an issue or send me an email; it’d mean a lot to me.

Creator

Jeevanandam M. (jeeva@myjeeva.com)

Contributors

Have a look on Contributors page.

License

Resty released under MIT license, refer LICENSE file.