resty

package module
v3.0.0-...-48a1a59 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2024 License: MIT Imports: 43 Imported by: 0

README ¶

Resty

Simple HTTP and REST client library for Go (inspired by Ruby rest-client)

Features section describes in detail about Resty capabilities

Build Status Code Coverage Go Report Card Release Version GoDoc License Mentioned in Awesome Go

News

  • v2.15.2 released and tagged on Sep 21, 2024.
  • 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
    • Native *http.Request instance may be accessed during middleware and request execution via Request.RawRequest
    • Request Body can be read multiple times via Request.RawRequest.GetBody()
  • 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 TODO move it
  • 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 middleware
    • 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
      • Since v2.4.0, trace info contains a RequestAttempt value, and the Request object contains an Attempt attribute
    • Supports on-demand CURL command generation, see Client.EnableGenerateCurlOnDebug, Request.EnableGenerateCurlOnDebug. It requires debug mode to be enabled.
    • 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, also HTTP/3 can be used with Resty, see this comment
  • Bazel support
  • Easily mock Resty for testing, for e.g.
  • Well tested client library

Included Batteries

  • Redirect Policies - see how to use
    • NoRedirectPolicy
    • FlexibleRedirectPolicy
    • DomainCheckRedirectPolicy
    • etc. more info
  • Retry Mechanism how to use
    • Backoff Retry
    • Conditional Retry
    • Since v2.6.0, Retry Hooks - Client, Request
  • SRV Record based request instead of Host URL how to use TODO move it
  • etc (upcoming - throw your idea's here).
  • Load Balancer - TODO Add documentation before release
Supported Go Versions

Recommended to use go1.20 and above.

Initially Resty started supporting go modules since v1.10.0 release.

Starting Resty v2 and higher versions, it fully embraces go modules package release. It requires a Go version capable of understanding /vN suffixed imports:

  • 1.9.7+
  • 1.10.3+
  • 1.11+

It might be beneficial for your project 😄

Resty author also published following projects for Go Community.

  • go-model - Robust & Easy to use model mapper and utility methods for Go struct.

Installation

# Go Modules
require github.com/go-resty/resty/v2 v2.15.2

Usage

The following samples will assist you to become as comfortable as possible with resty library.

// Import resty into your code and refer it as `resty`.
import "github.com/go-resty/resty/v2"
Simple GET
// Create a Resty Client
client := resty.New()

resp, err := client.R().
    EnableTrace().
    Get("https://httpbin.org/get")

// Explore response object
fmt.Println("Response Info:")
fmt.Println("  Error      :", err)
fmt.Println("  Status Code:", resp.StatusCode())
fmt.Println("  Status     :", resp.Status())
fmt.Println("  Proto      :", resp.Proto())
fmt.Println("  Time       :", resp.Time())
fmt.Println("  Received At:", resp.ReceivedAt())
fmt.Println("  Body       :\n", resp)
fmt.Println()

// Explore trace info
fmt.Println("Request Trace Info:")
ti := resp.Request.TraceInfo()
fmt.Println("  DNSLookup     :", ti.DNSLookup)
fmt.Println("  ConnTime      :", ti.ConnTime)
fmt.Println("  TCPConnTime   :", ti.TCPConnTime)
fmt.Println("  TLSHandshake  :", ti.TLSHandshake)
fmt.Println("  ServerTime    :", ti.ServerTime)
fmt.Println("  ResponseTime  :", ti.ResponseTime)
fmt.Println("  TotalTime     :", ti.TotalTime)
fmt.Println("  IsConnReused  :", ti.IsConnReused)
fmt.Println("  IsConnWasIdle :", ti.IsConnWasIdle)
fmt.Println("  ConnIdleTime  :", ti.ConnIdleTime)
fmt.Println("  RequestAttempt:", ti.RequestAttempt)
fmt.Println("  RemoteAddr    :", ti.RemoteAddr.String())

/* Output
Response Info:
  Error      : <nil>
  Status Code: 200
  Status     : 200 OK
  Proto      : HTTP/2.0
  Time       : 457.034718ms
  Received At: 2020-09-14 15:35:29.784681 -0700 PDT m=+0.458137045
  Body       :
  {
    "args": {},
    "headers": {
      "Accept-Encoding": "gzip",
      "Host": "httpbin.org",
      "User-Agent": "go-resty/2.4.0 (https://github.com/go-resty/resty)",
      "X-Amzn-Trace-Id": "Root=1-5f5ff031-000ff6292204aa6898e4de49"
    },
    "origin": "0.0.0.0",
    "url": "https://httpbin.org/get"
  }

Request Trace Info:
  DNSLookup     : 4.074657ms
  ConnTime      : 381.709936ms
  TCPConnTime   : 77.428048ms
  TLSHandshake  : 299.623597ms
  ServerTime    : 75.414703ms
  ResponseTime  : 79.337µs
  TotalTime     : 457.034718ms
  IsConnReused  : false
  IsConnWasIdle : false
  ConnIdleTime  : 0s
  RequestAttempt: 1
  RemoteAddr    : 3.221.81.55:443
*/
Enhanced GET
// Create a Resty Client
client := resty.New()

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")


// Sample of using Request.SetQueryString method
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")


// If necessary, you can force response content type to tell Resty to parse a JSON response into your struct
resp, err := client.R().
      SetResult(result).
      ForceContentType("application/json").
      Get("v2/alpine/manifests/latest")
Various POST method combinations
// Create a Resty Client
client := resty.New()

// POST JSON string
// No need to set content type, if you have client level setting
resp, err := client.R().
      SetHeader("Content-Type", "application/json").
      SetBody(`{"username":"testuser", "password":"testpass"}`).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      Post("https://myapp.com/login")

// POST []byte array
// No need to set content type, if you have client level setting
resp, err := client.R().
      SetHeader("Content-Type", "application/json").
      SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      Post("https://myapp.com/login")

// POST Struct, default is JSON content type. No need to set one
resp, err := client.R().
      SetBody(User{Username: "testuser", Password: "testpass"}).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      SetError(&AuthError{}).       // or SetError(AuthError{}).
      Post("https://myapp.com/login")

// POST Map, default is JSON content type. No need to set one
resp, err := client.R().
      SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}).
      SetResult(&AuthSuccess{}).    // or SetResult(AuthSuccess{}).
      SetError(&AuthError{}).       // or SetError(AuthError{}).
      Post("https://myapp.com/login")

// POST of raw bytes for file upload. For example: upload file to Dropbox
fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf")

// See we are not setting content-type header, since go-resty automatically detects Content-Type for you
resp, err := client.R().
      SetBody(fileBytes).
      SetContentLength(true).          // Dropbox expects this value
      SetAuthToken("<your-auth-token>").
      SetError(&DropboxError{}).       // or SetError(DropboxError{}).
      Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // for upload Dropbox supports PUT too

// Note: resty detects Content-Type for request body/payload if content type header is not set.
//   * For struct and map data type defaults to 'application/json'
//   * Fallback is plain text content type
Sample PUT

You can use various combinations of PUT method call like demonstrated for POST.

// Note: This is one sample of PUT method usage, refer POST for more combination

// Create a Resty Client
client := resty.New()

// Request goes as JSON content type
// No need to set auth token, error, if you have client level settings
resp, err := client.R().
      SetBody(Article{
        Title: "go-resty",
        Content: "This is my article content, oh ya!",
        Author: "Jeevanandam M",
        Tags: []string{"article", "sample", "resty"},
      }).
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // or SetError(Error{}).
      Put("https://myapp.com/article/1234")
Sample PATCH

You can use various combinations of PATCH method call like demonstrated for POST.

// Note: This is one sample of PUT method usage, refer POST for more combination

// Create a Resty Client
client := resty.New()

// Request goes as JSON content type
// No need to set auth token, error, if you have client level settings
resp, err := client.R().
      SetBody(Article{
        Tags: []string{"new tag1", "new tag2"},
      }).
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // or SetError(Error{}).
      Patch("https://myapp.com/articles/1234")
Sample DELETE, HEAD, OPTIONS
// Create a Resty Client
client := resty.New()

// DELETE a article
// No need to set auth token, error, if you have client level settings
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // or SetError(Error{}).
      Delete("https://myapp.com/articles/1234")

// DELETE a articles with payload/body as a JSON string
// No need to set auth token, error, if you have client level settings
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      SetError(&Error{}).       // or SetError(Error{}).
      SetHeader("Content-Type", "application/json").
      SetBody(`{article_ids: [1002, 1006, 1007, 87683, 45432] }`).
      Delete("https://myapp.com/articles")

// HEAD of resource
// No need to set auth token, if you have client level settings
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      Head("https://myapp.com/videos/hi-res-video")

// OPTIONS of resource
// No need to set auth token, if you have client level settings
resp, err := client.R().
      SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
      Options("https://myapp.com/servers/nyc-dc-01")
Override JSON & XML Marshal/Unmarshal

User could register choice of JSON/XML library into resty or write your own. By default resty registers standard encoding/json and encoding/xml respectively.

// Example of registering json-iterator
import jsoniter "github.com/json-iterator/go"

json := jsoniter.ConfigCompatibleWithStandardLibrary

client := resty.New().
    SetJSONMarshaler(json.Marshal).
    SetJSONUnmarshaler(json.Unmarshal)

// similarly user could do for XML too with -
client.SetXMLMarshaler(xml.Marshal).
    SetXMLUnmarshaler(xml.Unmarshal)

Multipart File(s) upload

Using io.Reader
profileImgBytes, _ := os.ReadFile("/Users/jeeva/test-img.png")
notesBytes, _ := os.ReadFile("/Users/jeeva/text-file.txt")

// Create a Resty Client
client := resty.New()

resp, err := client.R().
      SetFileReader("profile_img", "test-img.png", bytes.NewReader(profileImgBytes)).
      SetFileReader("notes", "text-file.txt", bytes.NewReader(notesBytes)).
      SetFormData(map[string]string{
          "first_name": "Jeevanandam",
          "last_name": "M",
      }).
      Post("http://myapp.com/upload")
Using File directly from Path
// Create a Resty Client
client := resty.New()

// Single file scenario
resp, err := client.R().
      SetFile("profile_img", "/Users/jeeva/test-img.png").
      Post("http://myapp.com/upload")

// Multiple files scenario
resp, err := client.R().
      SetFiles(map[string]string{
        "profile_img": "/Users/jeeva/test-img.png",
        "notes": "/Users/jeeva/text-file.txt",
      }).
      Post("http://myapp.com/upload")

// Multipart of form fields and files
resp, err := client.R().
      SetFiles(map[string]string{
        "profile_img": "/Users/jeeva/test-img.png",
        "notes": "/Users/jeeva/text-file.txt",
      }).
      SetFormData(map[string]string{
        "first_name": "Jeevanandam",
        "last_name": "M",
        "zip_code": "00001",
        "city": "my city",
        "access_token": "C6A79608-782F-4ED0-A11D-BD82FAD829CD",
      }).
      Post("http://myapp.com/profile")
Sample Form submission
// Create a Resty Client
client := resty.New()

// just mentioning about POST as an example with simple flow
// User Login
resp, err := client.R().
      SetFormData(map[string]string{
        "username": "jeeva",
        "password": "mypass",
      }).
      Post("http://myapp.com/login")

// Followed by profile update
resp, err := client.R().
      SetFormData(map[string]string{
        "first_name": "Jeevanandam",
        "last_name": "M",
        "zip_code": "00001",
        "city": "new city update",
      }).
      Post("http://myapp.com/profile")

// Multi value form data
criteria := url.Values{
  "search_criteria": []string{"book", "glass", "pencil"},
}
resp, err := client.R().
      SetFormDataFromValues(criteria).
      Post("http://myapp.com/search")
Save HTTP Response into File
// Create a Resty Client
client := resty.New()

// Setting output directory path, If directory not exists then resty creates one!
// This is optional one, if you're planning using absolute path in
// `Request.SetOutput` and can used together.
client.SetOutputDirectory("/Users/jeeva/Downloads")

// HTTP response gets saved into file, similar to curl -o flag
_, err := client.R().
          SetOutput("plugin/ReplyWithHeader-v5.1-beta.zip").
          Get("http://bit.ly/1LouEKr")

// OR using absolute path
// Note: output directory path is not used for absolute path
_, err := client.R().
          SetOutput("/MyDownloads/plugin/ReplyWithHeader-v5.1-beta.zip").
          Get("http://bit.ly/1LouEKr")
Request URL Path Params

Resty provides easy to use dynamic request URL path params. Params can be set at client and request level. Client level params value can be overridden at request level.

// Create a Resty Client
client := resty.New()

client.R().SetPathParams(map[string]string{
   "userId": "sample@sample.com",
   "subAccountId": "100002",
}).
Get("/v1/users/{userId}/{subAccountId}/details")

// Result:
//   Composed URL - /v1/users/sample@sample.com/100002/details
Request and Response Middleware

Resty provides middleware ability to manipulate for Request and Response. It is more flexible than callback approach.

// Create a Resty Client
client := resty.New()

// Registering Request Middleware
client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error { // TODO update docs
    // Now you have access to Client and current Request object
    // manipulate it as per your need

    return nil  // if its success otherwise return error
  })

// Registering Response Middleware
client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error { // TODO update docs
    // Now you have access to Client and current Response object
    // manipulate it as per your need

    return nil  // if its success otherwise return error
  })
OnError Hooks

Resty provides OnError hooks that may be called because:

  • The client failed to send the request due to connection timeout, TLS handshake failure, etc...
  • The request was retried the maximum amount of times, and still failed.

If there was a response from the server, the original error will be wrapped in *resty.ResponseError which contains the last response received.

// Create a Resty Client
client := resty.New()

client.OnError(func(req *resty.Request, err error) {
  if v, ok := err.(*resty.ResponseError); ok {
    // v.Response contains the last response from the server
    // v.Err contains the original error
  }
  // Log the error, increment a metric, etc...
})
Generate CURL Command

Refer: curl_cmd_test.go

// Create a Resty Client
client := resty.New()

resp, err := client.R().
    SetDebug(true).
    EnableGenerateCurlOnDebug(). // CURL command generated when debug mode enabled with this option
    SetBody(map[string]string{"name": "Alex"}).
    Post("https://httpbin.org/post")

curlCmdExecuted := resp.Request.GenerateCurlCommand()

// Explore curl command
fmt.Println("Curl Command:\n  ", curlCmdExecuted+"\n")

/* Output
Curl Command:
   curl -X POST -H 'Content-Type: application/json' -H 'User-Agent: go-resty/2.14.0 (https://github.com/go-resty/resty)' -d '{"name":"Alex"}' https://httpbin.org/post
*/
Redirect Policy

Resty provides few ready to use redirect policy(s) also it supports multiple policies together.

// Create a Resty Client
client := resty.New()

// Assign Client Redirect Policy. Create one as per you need
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(15))

// Wanna multiple policies such as redirect count, domain name check, etc
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20),
                        resty.DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))
Custom Redirect Policy

Implement RedirectPolicy interface and register it with resty client. Have a look redirect.go for more information.

// Create a Resty Client
client := resty.New()

// Using raw func into resty.SetRedirectPolicy
client.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
  // Implement your logic here

  // return nil for continue redirect otherwise return error to stop/prevent redirect
  return nil
}))

//---------------------------------------------------

// Using struct create more flexible redirect policy
type CustomRedirectPolicy struct {
  // variables goes here
}

func (c *CustomRedirectPolicy) Apply(req *http.Request, via []*http.Request) error {
  // Implement your logic here

  // return nil for continue redirect otherwise return error to stop/prevent redirect
  return nil
}

// Registering in resty
client.SetRedirectPolicy(CustomRedirectPolicy{/* initialize variables */})
Custom Root Certificates and Client Certificates
// Create a Resty Client
client := resty.New()

// Custom Root certificates, just supply .pem file.
// you can add one or more root certificates, its get appended
client.SetRootCertificate("/path/to/root/pemFile1.pem")
client.SetRootCertificate("/path/to/root/pemFile2.pem")
// ... and so on!

// Adding Client Certificates, you add one or more certificates
// Sample for creating certificate object
// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
cert1, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
if err != nil {
  log.Fatalf("ERROR client certificate: %s", err)
}
// ...

// You add one or more certificates
client.SetCertificates(cert1, cert2, cert3)
Custom Root Certificates and Client Certificates from string
// Custom Root certificates from string
// You can pass you certificates through env variables as strings
// you can add one or more root certificates, its get appended
client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----")
client.SetRootCertificateFromString("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----")
// ... and so on!

// Adding Client Certificates, you add one or more certificates
// Sample for creating certificate object
// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
cert1, err := tls.X509KeyPair([]byte("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----"), []byte("-----BEGIN CERTIFICATE-----content-----END CERTIFICATE-----"))
if err != nil {
  log.Fatalf("ERROR client certificate: %s", err)
}
// ...

// You add one or more certificates
client.SetCertificates(cert1, cert2, cert3)
Proxy Settings

Default Go supports Proxy via environment variable HTTP_PROXY. Resty provides support via SetProxy & RemoveProxy. Choose as per your need.

Client Level Proxy settings applied to all the request

// Create a Resty Client
client := resty.New()

// Setting a Proxy URL and Port
client.SetProxy("http://proxyserver:8888")

// Want to remove proxy setting
client.RemoveProxy()
Retries

Resty uses backoff to increase retry intervals after each attempt.

TODO update retry docs

Usage example:

// Create a Resty Client
client := resty.New()

// Retries are configured per client
client.
    // Set retry count to non zero to enable retries
    SetRetryCount(3).
    // You can override initial retry wait time.
    // Default is 100 milliseconds.
    SetRetryWaitTime(5 * time.Second).
    // MaxWaitTime can be overridden as well.
    // Default is 2 seconds.
    SetRetryMaxWaitTime(20 * time.Second).
    // SetRetryAfter sets callback to calculate wait time between retries.
    // Default (nil) implies exponential backoff with jitter
    SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) {
        return 0, errors.New("quota exceeded")
    })

By default, resty will retry requests that return a non-nil error during execution. Therefore, the above setup will result in resty retrying requests with non-nil errors up to 3 times, with the delay increasing after each attempt.

You can optionally provide client with custom retry conditions:

// Create a Resty Client
client := resty.New()

client.AddRetryCondition(
    // RetryConditionFunc type is for retry condition function
    // input: non-nil Response OR request execution error
    func(r *resty.Response, err error) bool {
        return r.StatusCode() == http.StatusTooManyRequests
    },
)

The above example will make resty retry requests that end with a 429 Too Many Requests status code. It's important to note that when you specify conditions using AddRetryCondition, it will override the default retry behavior, which retries on errors encountered during the request. If you want to retry on errors encountered during the request, similar to the default behavior, you'll need to configure it as follows:

// Create a Resty Client
client := resty.New()

client.AddRetryCondition(
    func(r *resty.Response, err error) bool {
        // Including "err != nil" emulates the default retry behavior for errors encountered during the request.
        return err != nil || r.StatusCode() == http.StatusTooManyRequests
    },
)

Multiple retry conditions can be added. Note that if multiple conditions are specified, a retry will occur if any of the conditions are met.

It is also possible to use resty.Backoff(...) to get arbitrary retry scenarios implemented. Reference.

Allow GET request with Payload
// Create a Resty Client
client := resty.New()

// Allow GET request with Payload. This is disabled by default.
client.SetAllowGetMethodPayload(true)
Wanna Multiple Clients
// Here you go!
// Client 1
client1 := resty.New()
client1.R().Get("http://httpbin.org")
// ...

// Client 2
client2 := resty.New()
client2.R().Head("http://httpbin.org")
// ...

// Bend it as per your need!!!
Remaining Client Settings & its Options
// Create a Resty Client
client := resty.New()

// Unique settings at Client level
//--------------------------------
// Enable debug mode
client.SetDebug(true)

// Assign Client TLSClientConfig
// One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial
client.SetTLSClientConfig(&tls.Config{ RootCAs: roots })

// or One can disable security check (https)
client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })

// Set client timeout as per your need
client.SetTimeout(1 * time.Minute)


// You can override all below settings and options at request level if you want to
//--------------------------------------------------------------------------------
// Host URL for all request. So you can use relative URL in the request
client.SetBaseURL("http://httpbin.org")

// Headers for all request
client.SetHeader("Accept", "application/json")
client.SetHeaders(map[string]string{
        "Content-Type": "application/json",
        "User-Agent": "My custom User Agent String",
      })

// Cookies for all request
client.SetCookie(&http.Cookie{
      Name:"go-resty",
      Value:"This is cookie value",
      Path: "/",
      Domain: "sample.com",
      MaxAge: 36000,
      HttpOnly: true,
      Secure: false,
    })
client.SetCookies(cookies)

// URL query parameters for all request
client.SetQueryParam("user_id", "00001")
client.SetQueryParams(map[string]string{ // sample of those who use this manner
      "api_key": "api-key-here",
      "api_secret": "api-secret",
    })
client.R().SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")

// Form data for all request. Typically used with POST and PUT
client.SetFormData(map[string]string{
    "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
  })

// Basic Auth for all request
client.SetBasicAuth("myuser", "mypass")

// Bearer Auth Token for all request
client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")

// Enabling Content length value for all request
client.SetContentLength(true)

// Registering global Error object structure for JSON/XML request
client.SetError(&Error{})    // or resty.SetError(Error{})
Unix Socket
unixSocket := "/var/run/my_socket.sock"

// Create a Go's http.Transport so we can set it in resty.
transport := http.Transport{
	Dial: func(_, _ string) (net.Conn, error) {
		return net.Dial("unix", unixSocket)
	},
}

// Create a Resty Client
client := resty.New()

// Set the previous transport that we created, set the scheme of the communication to the
// socket and set the unixSocket as the HostURL.
client.SetTransport(&transport).SetScheme("http").SetBaseURL(unixSocket)

// No need to write the host's URL on the request, just the path.
client.R().Get("http://localhost/index.html")
Bazel Support

Resty can be built, tested and depended upon via Bazel. For example, to run all tests:

bazel test :resty_test
Mocking http requests using httpmock library

In order to mock the http requests when testing your application you could use the httpmock library.

When using the default resty client, you should pass the client to the library as follow:

// Create a Resty Client
client := resty.New()

// Get the underlying HTTP Client and set it to Mock
httpmock.ActivateNonDefault(client.GetClient())

More detailed example of mocking resty http requests using ginko could be found here.

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)

Core Team

Have a look on Members page.

Contributors

Have a look on Contributors page.

License

Resty released under MIT license, refer LICENSE file.

Documentation ¶

Overview ¶

Package resty provides Simple HTTP and REST client library for Go.

Example (ClientCertificates) ¶
// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
if err != nil {
	log.Fatalf("ERROR client certificate: %s", err)
}

// Create a resty client
client := resty.New()

client.SetCertificates(cert)
Example (CustomRootCertificate) ¶
// Create a resty client
client := resty.New()
client.SetRootCertificate("/path/to/root/pemFile.pem")
Example (DropboxUpload) ¶
// For example: upload file to Dropbox
// POST of raw bytes for file upload.
fileBytes, _ := os.ReadFile("/Users/jeeva/mydocument.pdf")

// Create a resty client
client := resty.New()

// See we are not setting content-type header, since go-resty automatically detects Content-Type for you
resp, err := client.R().
	SetBody(fileBytes).     // resty autodetects content type
	SetContentLength(true). // Dropbox expects this value
	SetAuthToken("<your-auth-token>").
	SetError(DropboxError{}).
	Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // you can use PUT method too dropbox supports it

// Output print
fmt.Printf("\nError: %v\n", err)
fmt.Printf("Time: %v\n", resp.Time())
fmt.Printf("Body: %v\n", resp)
Example (EnhancedGet) ¶
// Create a resty client
client := resty.New()

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")

printOutput(resp, err)
Example (Get) ¶
// Create a resty client
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 Body: %v", resp)
fmt.Printf("\nResponse Time: %v", resp.Time())
fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt())
Example (Post) ¶
// Create a resty client
client := resty.New()

// POST JSON string
// No need to set content type, if you have client level setting
resp, err := client.R().
	SetHeader("Content-Type", "application/json").
	SetBody(`{"username":"testuser", "password":"testpass"}`).
	SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}).
	Post("https://myapp.com/login")

printOutput(resp, err)

// POST []byte array
// No need to set content type, if you have client level setting
resp1, err1 := client.R().
	SetHeader("Content-Type", "application/json").
	SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)).
	SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}).
	Post("https://myapp.com/login")

printOutput(resp1, err1)

type User struct {
	Username, Password string
}
// POST Struct, default is JSON content type. No need to set one
resp2, err2 := client.R().
	SetBody(User{Username: "testuser", Password: "testpass"}).
	SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
	SetError(&AuthError{}).    // or SetError(AuthError{}).
	Post("https://myapp.com/login")

printOutput(resp2, err2)

// POST Map, default is JSON content type. No need to set one
resp3, err3 := client.R().
	SetBody(map[string]any{"username": "testuser", "password": "testpass"}).
	SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}).
	SetError(&AuthError{}).    // or SetError(AuthError{}).
	Post("https://myapp.com/login")

printOutput(resp3, err3)
Example (Put) ¶
// Create a resty client
client := resty.New()

// Just one sample of PUT, refer POST for more combination
// request goes as JSON content type
// No need to set auth token, error, if you have client level settings
resp, err := client.R().
	SetBody(Article{
		Title:   "go-resty",
		Content: "This is my article content, oh ya!",
		Author:  "Jeevanandam M",
		Tags:    []string{"article", "sample", "resty"},
	}).
	SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD").
	SetError(&Error{}). // or SetError(Error{}).
	Put("https://myapp.com/article/1234")

printOutput(resp, err)
Example (Socks5Proxy) ¶
// create a dialer
dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:9150", nil, proxy.Direct)
if err != nil {
	log.Fatalf("Unable to obtain proxy dialer: %v\n", err)
}

// create a transport
ptransport := &http.Transport{Dial: dialer.Dial}

// Create a resty client
client := resty.New()

// set transport into resty
client.SetTransport(ptransport)

resp, err := client.R().Get("http://check.torproject.org")
fmt.Println(err, resp)

Index ¶

Examples ¶

Constants ¶

View Source
const (
	// MethodGet HTTP method
	MethodGet = "GET"

	// MethodPost HTTP method
	MethodPost = "POST"

	// MethodPut HTTP method
	MethodPut = "PUT"

	// MethodDelete HTTP method
	MethodDelete = "DELETE"

	// MethodPatch HTTP method
	MethodPatch = "PATCH"

	// MethodHead HTTP method
	MethodHead = "HEAD"

	// MethodOptions HTTP method
	MethodOptions = "OPTIONS"

	// MethodTrace HTTP method
	MethodTrace = "TRACE"
)
View Source
const Version = "3.0.0-dev"

Version # of resty

Variables ¶

View Source
var (
	ErrNotHttpTransportType       = errors.New("resty: not a http.Transport type")
	ErrUnsupportedRequestBodyKind = errors.New("resty: unsupported request body kind")
)
View Source
var (
	ErrDigestBadChallenge    = errors.New("resty: digest: challenge is bad")
	ErrDigestInvalidCharset  = errors.New("resty: digest: invalid charset")
	ErrDigestAlgNotSupported = errors.New("resty: digest: algorithm is not supported")
	ErrDigestQopNotSupported = errors.New("resty: digest: qop is not supported")
)
View Source
var (
	ErrContentDecompressorNotFound = errors.New("resty: content decoder not found")
)
View Source
var ErrNoActiveHost = errors.New("resty: no active host")

ErrNoActiveHost error returned when all hosts are inactive on the load balancer

View Source
var ErrReadExceedsThresholdLimit = errors.New("resty: read exceeds the threshold limit")

Functions ¶

func AutoParseResponseMiddleware ¶

func AutoParseResponseMiddleware(c *Client, res *Response) (err error)

AutoParseResponseMiddleware method is used to parse the response body automatically based on registered HTTP response `Content-Type` decoder, see Client.AddContentTypeDecoder; if Request.SetResult, Request.SetError, or Client.SetError is used

func GenerateCurlRequestMiddleware ¶

func GenerateCurlRequestMiddleware(c *Client, r *Request) (err error)

GenerateCurlRequestMiddleware method is used to perform CURL command generation during a request preparation

See, Client.SetGenerateCurlOnDebug, Request.SetGenerateCurlOnDebug

func PrepareRequestMiddleware ¶

func PrepareRequestMiddleware(c *Client, r *Request) error

PrepareRequestMiddleware method is used to prepare HTTP requests from user provides request values. Request preparation fails if any error occurs

func SaveToFileResponseMiddleware ¶

func SaveToFileResponseMiddleware(c *Client, res *Response) error

SaveToFileResponseMiddleware method used to write HTTP response body into given file details via Request.SetOutputFile

Types ¶

type CertWatcherOptions ¶

type CertWatcherOptions struct {
	// PoolInterval is the frequency at which resty will check if the PEM file needs to be reloaded.
	// Default is 24 hours.
	PoolInterval time.Duration
}

CertWatcherOptions allows configuring a watcher that reloads dynamically TLS certs.

type Client ¶

type Client struct {
	// contains filtered or unexported fields
}

Client struct is used to create a Resty client with client-level settings, these settings apply to all the requests raised from the client.

Resty also provides an option to override most of the client settings at Request level.

func New ¶

func New() *Client

New method creates a new Resty client.

Example ¶
// Creating client1
client1 := resty.New()
resp1, err1 := client1.R().Get("http://httpbin.org/get")
fmt.Println(resp1, err1)

// Creating client2
client2 := resty.New()
resp2, err2 := client2.R().Get("http://httpbin.org/get")
fmt.Println(resp2, err2)

func NewWithClient ¶

func NewWithClient(hc *http.Client) *Client

NewWithClient method creates a new Resty client with given http.Client.

func NewWithDialer ¶

func NewWithDialer(dialer *net.Dialer) *Client

NewWithDialer method creates a new Resty client with given Local Address to dial from.

func NewWithDialerAndTransportSettings ¶

func NewWithDialerAndTransportSettings(dialer *net.Dialer, transportSettings *TransportSettings) *Client

NewWithDialerAndTransportSettings method creates a new Resty client with given Local Address to dial from.

func NewWithLocalAddr ¶

func NewWithLocalAddr(localAddr net.Addr) *Client

NewWithLocalAddr method creates a new Resty client with the given Local Address.

func NewWithTransportSettings ¶

func NewWithTransportSettings(transportSettings *TransportSettings) *Client

NewWithTransportSettings method creates a new Resty client with provided timeout values.

func (*Client) AddContentDecompressor ¶

func (c *Client) AddContentDecompressor(k string, d ContentDecompressor) *Client

AddContentDecompressor method adds the user-provided Content-Encoding (RFC 9110) decompressor and directive into a client.

NOTE: It overwrites the decompressor function if the given Content-Encoding directive already exists.

func (*Client) AddContentTypeDecoder ¶

func (c *Client) AddContentTypeDecoder(ct string, d ContentTypeDecoder) *Client

AddContentTypeDecoder method adds the user-provided Content-Type decoder into a client.

NOTE: It overwrites the decoder function if the given Content-Type key already exists.

func (*Client) AddContentTypeEncoder ¶

func (c *Client) AddContentTypeEncoder(ct string, e ContentTypeEncoder) *Client

AddContentTypeEncoder method adds the user-provided Content-Type encoder into a client.

NOTE: It overwrites the encoder function if the given Content-Type key already exists.

func (*Client) AddRequestMiddleware ¶

func (c *Client) AddRequestMiddleware(m RequestMiddleware) *Client

AddRequestMiddleware method appends a request middleware to the before request chain. After all requests, middlewares are applied, and the request is sent to the host server.

client.AddRequestMiddleware(func(c *resty.Client, r *resty.Request) error {
	// Now you have access to the Client and Request instance
	// manipulate it as per your need

	return nil 	// if its successful otherwise return error
})

func (*Client) AddResponseMiddleware ¶

func (c *Client) AddResponseMiddleware(m ResponseMiddleware) *Client

AddResponseMiddleware method appends response middleware to the after-response chain. All the response middlewares are applied; once we receive a response from the host server.

client.AddResponseMiddleware(func(c *resty.Client, r *resty.Response) error {
	// Now you have access to the Client and Response instance
	// Also, you could access request via Response.Request i.e., r.Request
	// manipulate it as per your need

	return nil 	// if its successful otherwise return error
})

func (*Client) AddRetryCondition ¶

func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client

AddRetryCondition method adds a retry condition function to an array of functions that are checked to determine if the request is retried. The request will retry if any functions return true and the error is nil.

NOTE: These retry conditions are applied on all requests made using this Client. For Request specific retry conditions, check Request.AddRetryCondition

func (*Client) AddRetryHook ¶

func (c *Client) AddRetryHook(hook RetryHookFunc) *Client

AddRetryHook adds a side-effecting retry hook to an array of hooks that will be executed on each retry.

func (*Client) AllowMethodDeletePayload ¶

func (c *Client) AllowMethodDeletePayload() bool

AllowMethodDeletePayload method returns `true` if the client is enabled to allow payload with DELETE method; otherwise, it is `false`.

More info, refer to GH#881

func (*Client) AllowMethodGetPayload ¶

func (c *Client) AllowMethodGetPayload() bool

AllowMethodGetPayload method returns `true` if the client is enabled to allow payload with GET method; otherwise, it is `false`.

func (*Client) AllowNonIdempotentRetry ¶

func (c *Client) AllowNonIdempotentRetry() bool

AllowNonIdempotentRetry method returns true if the client is enabled to allow non-idempotent HTTP methods retry; otherwise, it is `false`

Default value is `false`

func (*Client) AuthScheme ¶

func (c *Client) AuthScheme() string

AuthScheme method returns the auth scheme name set in the client instance.

See Client.SetAuthScheme, Request.SetAuthScheme.

func (*Client) AuthToken ¶

func (c *Client) AuthToken() string

AuthToken method returns the auth token value registered in the client instance.

func (*Client) BaseURL ¶

func (c *Client) BaseURL() string

BaseURL method returns the Base URL value from the client instance.

func (*Client) Client ¶

func (c *Client) Client() *http.Client

Client method returns the underlying Go http.Client used by the Resty.

func (*Client) Clone ¶

func (c *Client) Clone(ctx context.Context) *Client

Clone method returns a clone of the original client.

NOTE: Use with care:

  • Interface values are not deeply cloned. Thus, both the original and the clone will use the same value.
  • It is not safe for concurrent use. You should only use this method when you are sure that any other concurrent process is not using the client.

func (*Client) Close ¶

func (c *Client) Close() error

Close method performs cleanup and closure activities on the client instance

func (*Client) ContentDecompressorKeys ¶

func (c *Client) ContentDecompressorKeys() string

ContentDecompressorKeys method returns all the registered content-encoding decompressors keys as comma-separated string.

func (*Client) ContentDecompressors ¶

func (c *Client) ContentDecompressors() map[string]ContentDecompressor

ContentDecompressors method returns all the registered content-encoding decompressors.

func (*Client) ContentTypeDecoders ¶

func (c *Client) ContentTypeDecoders() map[string]ContentTypeDecoder

ContentTypeDecoders method returns all the registered content type decoders.

func (*Client) ContentTypeEncoders ¶

func (c *Client) ContentTypeEncoders() map[string]ContentTypeEncoder

ContentTypeEncoders method returns all the registered content type encoders.

func (*Client) Context ¶

func (c *Client) Context() context.Context

Context method returns the context.Context from the client instance.

func (*Client) CookieJar ¶

func (c *Client) CookieJar() http.CookieJar

CookieJar method returns the HTTP cookie jar instance from the underlying Go HTTP Client.

func (*Client) Cookies ¶

func (c *Client) Cookies() []*http.Cookie

Cookies method returns all cookies registered in the client instance.

func (*Client) DebugBodyLimit ¶

func (c *Client) DebugBodyLimit() int

DebugBodyLimit method returns the debug body limit value set on the client instance

func (*Client) DisableDebug ¶

func (c *Client) DisableDebug() *Client

DisableDebug method is a helper method for Client.SetDebug

func (*Client) DisableGenerateCurlOnDebug ¶

func (c *Client) DisableGenerateCurlOnDebug() *Client

DisableGenerateCurlOnDebug method disables the option set by Client.EnableGenerateCurlOnDebug.

func (*Client) DisableRetryDefaultConditions ¶

func (c *Client) DisableRetryDefaultConditions() *Client

DisableRetryDefaultConditions method disables the Resty's default retry conditions

func (*Client) DisableTrace ¶

func (c *Client) DisableTrace() *Client

DisableTrace method disables the Resty client trace. Refer to Client.EnableTrace.

func (*Client) EnableDebug ¶

func (c *Client) EnableDebug() *Client

EnableDebug method is a helper method for Client.SetDebug

func (*Client) EnableGenerateCurlOnDebug ¶

func (c *Client) EnableGenerateCurlOnDebug() *Client

EnableGenerateCurlOnDebug method enables the generation of CURL commands in the debug log. It works in conjunction with debug mode.

NOTE: Use with care.

  • Potential to leak sensitive data from Request and Response in the debug log.
  • Beware of memory usage since the request body is reread.

func (*Client) EnableRetryDefaultConditions ¶

func (c *Client) EnableRetryDefaultConditions() *Client

EnableRetryDefaultConditions method enables the Resty's default retry conditions

func (*Client) EnableTrace ¶

func (c *Client) EnableTrace() *Client

EnableTrace method enables the Resty client trace for the requests fired from the client using httptrace.ClientTrace and provides insights.

client := resty.New().EnableTrace()

resp, err := client.R().Get("https://httpbin.org/get")
fmt.Println("error:", err)
fmt.Println("Trace Info:", resp.Request.TraceInfo())

The method Request.EnableTrace is also available to get trace info for a single request.

func (*Client) Error ¶

func (c *Client) Error() reflect.Type

Error method returns the global or client common `Error` object type registered in the Resty.

func (*Client) FormData ¶

func (c *Client) FormData() url.Values

FormData method returns the form parameters and their values from the client instance.

func (*Client) HTTPTransport ¶

func (c *Client) HTTPTransport() (*http.Transport, error)

HTTPTransport method does type assertion and returns http.Transport from the client instance, if type assertion fails it returns an error

func (*Client) Header ¶

func (c *Client) Header() http.Header

Header method returns the headers from the client instance.

func (*Client) HeaderAuthorizationKey ¶

func (c *Client) HeaderAuthorizationKey() string

HeaderAuthorizationKey method returns the HTTP header name for Authorization from the client instance.

func (*Client) IsContentLength ¶

func (c *Client) IsContentLength() bool

IsContentLength method returns true if the user requests to set content length. Otherwise, it is false.

func (*Client) IsDebug ¶

func (c *Client) IsDebug() bool

IsDebug method returns `true` if the client is in debug mode; otherwise, it is `false`.

func (*Client) IsDisableWarn ¶

func (c *Client) IsDisableWarn() bool

IsDisableWarn method returns `true` if the warning message is disabled; otherwise, it is `false`.

func (*Client) IsProxySet ¶

func (c *Client) IsProxySet() bool

IsProxySet method returns the true is proxy is set from the Resty client; otherwise false. By default, the proxy is set from the environment variable; refer to http.ProxyFromEnvironment.

func (*Client) IsRetryDefaultConditions ¶

func (c *Client) IsRetryDefaultConditions() bool

IsRetryDefaultConditions method returns true if Resty's default retry conditions are enabled otherwise false

Default value is `true`

func (*Client) IsTrace ¶

func (c *Client) IsTrace() bool

IsTrace method returns true if the trace is enabled on the client instance; otherwise, it returns false.

func (*Client) LoadBalancer ¶

func (c *Client) LoadBalancer() LoadBalancer

LoadBalancer method returns the requestload balancer instance from the client instance. Otherwise returns nil.

func (*Client) Logger ¶

func (c *Client) Logger() Logger

Logger method returns the logger instance used by the client instance.

func (*Client) NewRequest ¶

func (c *Client) NewRequest() *Request

NewRequest method is an alias for method `R()`.

func (*Client) OnError ¶

func (c *Client) OnError(h ErrorHook) *Client

OnError method adds a callback that will be run whenever a request execution fails. This is called after all retries have been attempted (if any). If there was a response from the server, the error will be wrapped in ResponseError which has the last response received from the server.

client.OnError(func(req *resty.Request, err error) {
	if v, ok := err.(*resty.ResponseError); ok {
		// Do something with v.Response
	}
	// Log the error, increment a metric, etc...
})

Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.

NOTE:

  • Do not use Client setter methods within OnError hooks; deadlock will happen.

func (*Client) OnInvalid ¶

func (c *Client) OnInvalid(h ErrorHook) *Client

OnInvalid method adds a callback that will be run whenever a request execution fails before it starts because the request is invalid.

Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.

NOTE:

  • Do not use Client setter methods within OnInvalid hooks; deadlock will happen.

func (*Client) OnPanic ¶

func (c *Client) OnPanic(h ErrorHook) *Client

OnPanic method adds a callback that will be run whenever a request execution panics.

Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.

If an Client.OnSuccess, Client.OnError, or Client.OnInvalid callback panics, then exactly one rule can be violated.

NOTE:

  • Do not use Client setter methods within OnPanic hooks; deadlock will happen.

func (*Client) OnRequestDebugLog ¶

func (c *Client) OnRequestDebugLog(dlc DebugLogCallback) *Client

OnRequestDebugLog method sets the request debug log callback to the client instance. Registered callback gets called before the Resty logs the information.

func (*Client) OnResponseDebugLog ¶

func (c *Client) OnResponseDebugLog(dlc DebugLogCallback) *Client

OnResponseDebugLog method sets the response debug log callback to the client instance. Registered callback gets called before the Resty logs the information.

func (*Client) OnSuccess ¶

func (c *Client) OnSuccess(h SuccessHook) *Client

OnSuccess method adds a callback that will be run whenever a request execution succeeds. This is called after all retries have been attempted (if any).

Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.

NOTE:

  • Do not use Client setter methods within OnSuccess hooks; deadlock will happen.

func (*Client) OutputDirectory ¶

func (c *Client) OutputDirectory() string

OutputDirectory method returns the output directory value from the client.

func (*Client) PathParams ¶

func (c *Client) PathParams() map[string]string

PathParams method returns the path parameters from the client.

pathParams := client.PathParams()

func (*Client) ProxyURL ¶

func (c *Client) ProxyURL() *url.URL

ProxyURL method returns the proxy URL if set otherwise nil.

func (*Client) QueryParams ¶

func (c *Client) QueryParams() url.Values

QueryParams method returns all query parameters and their values from the client instance.

func (*Client) R ¶

func (c *Client) R() *Request

R method creates a new request instance; it's used for Get, Post, Put, Delete, Patch, Head, Options, etc.

func (*Client) RawPathParams ¶

func (c *Client) RawPathParams() map[string]string

RawPathParams method returns the raw path parameters from the client.

func (*Client) RemoveProxy ¶

func (c *Client) RemoveProxy() *Client

RemoveProxy method removes the proxy configuration from the Resty client

client.RemoveProxy()

func (*Client) ResponseBodyLimit ¶

func (c *Client) ResponseBodyLimit() int64

ResponseBodyLimit method returns the value max body size limit in bytes from the client instance.

func (*Client) ResponseBodyUnlimitedReads ¶

func (c *Client) ResponseBodyUnlimitedReads() bool

ResponseBodyUnlimitedReads method returns true if enabled. Otherwise, it returns false

func (*Client) RetryConditions ¶

func (c *Client) RetryConditions() []RetryConditionFunc

RetryConditions method returns all the retry condition functions.

func (*Client) RetryCount ¶

func (c *Client) RetryCount() int

RetryCount method returns the retry count value from the client instance.

func (*Client) RetryHooks ¶

func (c *Client) RetryHooks() []RetryHookFunc

RetryHooks method returns all the retry hook functions.

func (*Client) RetryMaxWaitTime ¶

func (c *Client) RetryMaxWaitTime() time.Duration

RetryMaxWaitTime method returns the retry max wait time that is used to sleep before retrying the request.

func (*Client) RetryStrategy ¶

func (c *Client) RetryStrategy() RetryStrategyFunc

RetryStrategy method returns the retry strategy function; otherwise, it is nil.

See Client.SetRetryStrategy

func (*Client) RetryWaitTime ¶

func (c *Client) RetryWaitTime() time.Duration

RetryWaitTime method returns the retry wait time that is used to sleep before retrying the request.

func (*Client) Scheme ¶

func (c *Client) Scheme() string

Scheme method returns custom scheme value from the client.

scheme := client.Scheme()

func (*Client) SetAllowMethodDeletePayload ¶

func (c *Client) SetAllowMethodDeletePayload(allow bool) *Client

SetAllowMethodDeletePayload method allows the DELETE method with payload on the Resty client. By default, Resty does not allow.

client.SetAllowMethodDeletePayload(true)

More info, refer to GH#881

It can be overridden at the request level. See Request.SetAllowMethodDeletePayload

func (*Client) SetAllowMethodGetPayload ¶

func (c *Client) SetAllowMethodGetPayload(allow bool) *Client

SetAllowMethodGetPayload method allows the GET method with payload on the Resty client. By default, Resty does not allow.

client.SetAllowMethodGetPayload(true)

It can be overridden at the request level. See Request.SetAllowMethodGetPayload

func (*Client) SetAllowNonIdempotentRetry ¶

func (c *Client) SetAllowNonIdempotentRetry(b bool) *Client

SetAllowNonIdempotentRetry method is used to enable/disable non-idempotent HTTP methods retry. By default, Resty only allows idempotent HTTP methods, see RFC 9110 Section 9.2.2, RFC 9110 Section 18.2

It can be overridden at request level, see Request.SetAllowNonIdempotentRetry

func (*Client) SetAuthScheme ¶

func (c *Client) SetAuthScheme(scheme string) *Client

SetAuthScheme method sets the auth scheme type in the HTTP request. For Example:

Authorization: <auth-scheme-value> <auth-token-value>

For Example: To set the scheme to use OAuth

client.SetAuthScheme("OAuth")

This auth scheme gets added to all the requests raised from this client instance. Also, it can be overridden at the request level.

Information about auth schemes can be found in RFC 7235, IANA HTTP Auth schemes.

See Request.SetAuthScheme.

func (*Client) SetAuthToken ¶

func (c *Client) SetAuthToken(token string) *Client

SetAuthToken method sets the auth token of the `Authorization` header for all HTTP requests. The default auth scheme is `Bearer`; it can be customized with the method Client.SetAuthScheme. For Example:

Authorization: <auth-scheme> <auth-token-value>

For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F

client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")

This auth token gets added to all the requests raised from this client instance. Also, it can be overridden at the request level.

See Request.SetAuthToken.

func (*Client) SetBaseURL ¶

func (c *Client) SetBaseURL(url string) *Client

SetBaseURL method sets the Base URL in the client instance. It will be used with a request raised from this client with a relative URL

// Setting HTTP address
client.SetBaseURL("http://myjeeva.com")

// Setting HTTPS address
client.SetBaseURL("https://myjeeva.com")

func (*Client) SetBasicAuth ¶

func (c *Client) SetBasicAuth(username, password string) *Client

SetBasicAuth method sets the basic authentication header in the HTTP request. For Example:

Authorization: Basic <base64-encoded-value>

For Example: To set the header for username "go-resty" and password "welcome"

client.SetBasicAuth("go-resty", "welcome")

This basic auth information is added to all requests from this client instance. It can also be overridden at the request level.

See Request.SetBasicAuth.

func (*Client) SetCertificates ¶

func (c *Client) SetCertificates(certs ...tls.Certificate) *Client

SetCertificates method helps to conveniently set client certificates into Resty.

Example ¶
// Parsing public/private key pair from a pair of files. The files must contain PEM encoded data.
cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
if err != nil {
	log.Fatalf("ERROR client certificate: %s", err)
}

// Create a resty client
client := resty.New()

client.SetCertificates(cert)

func (*Client) SetClientRootCertificate ¶

func (c *Client) SetClientRootCertificate(pemFilePath string) *Client

SetClientRootCertificate method helps to add one or more client's root certificates into the Resty client

client.SetClientRootCertificate("/path/to/root/pemFile.pem")

func (*Client) SetClientRootCertificateFromString ¶

func (c *Client) SetClientRootCertificateFromString(pemCerts string) *Client

SetClientRootCertificateFromString method helps to add one or more clients root certificates into the Resty client

client.SetClientRootCertificateFromString("pem certs content")

func (*Client) SetClientRootCertificateWatcher ¶

func (c *Client) SetClientRootCertificateWatcher(pemFilePath string, options *CertWatcherOptions) *Client

SetClientRootCertificateWatcher enables dynamic reloading of one or more client root certificates. It is designed for scenarios involving long-running Resty clients where certificates may be renewed. The caller is responsible for calling Close to stop the watcher.

client.SetClientRootCertificateWatcher("root-ca.crt", &CertWatcherOptions{
	PoolInterval: time.Hour * 24,
})
defer client.Close()

func (*Client) SetCloseConnection ¶

func (c *Client) SetCloseConnection(close bool) *Client

SetCloseConnection method sets variable `Close` in HTTP request struct with the given value. More info: https://golang.org/src/net/http/request.go

It can be overridden at the request level, see Request.SetCloseConnection

func (*Client) SetContentDecompressorKeys ¶

func (c *Client) SetContentDecompressorKeys(keys []string) *Client

SetContentDecompressorKeys method sets given Content-Encoding (RFC 9110) directives into the client instance.

It checks the given Content-Encoding exists in the ContentDecompressor list before assigning it, if it does not exist, it will skip that directive.

Use this method to overwrite the default order. If a new content decompressor is added, that directive will be the first.

func (*Client) SetContentLength ¶

func (c *Client) SetContentLength(l bool) *Client

SetContentLength method enables the HTTP header `Content-Length` value for every request. By default, Resty won't set `Content-Length`.

client.SetContentLength(true)

Also, you have the option to enable a particular request. See Request.SetContentLength

func (*Client) SetContext ¶

func (c *Client) SetContext(ctx context.Context) *Client

SetContext method sets the given context.Context in the client instance and it gets added to Request raised from this instance.

func (*Client) SetCookie ¶

func (c *Client) SetCookie(hc *http.Cookie) *Client

SetCookie method appends a single cookie to the client instance. These cookies will be added to all the requests from this client instance.

client.SetCookie(&http.Cookie{
	Name:"go-resty",
	Value:"This is cookie value",
})

func (*Client) SetCookieJar ¶

func (c *Client) SetCookieJar(jar http.CookieJar) *Client

SetCookieJar method sets custom http.CookieJar in the resty client. It's a way to override the default.

For Example, sometimes we don't want to save cookies in API mode so that we can remove the default CookieJar in resty client.

client.SetCookieJar(nil)

func (*Client) SetCookies ¶

func (c *Client) SetCookies(cs []*http.Cookie) *Client

SetCookies method sets an array of cookies in the client instance. These cookies will be added to all the requests from this client instance.

cookies := []*http.Cookie{
	&http.Cookie{
		Name:"go-resty-1",
		Value:"This is cookie 1 value",
	},
	&http.Cookie{
		Name:"go-resty-2",
		Value:"This is cookie 2 value",
	},
}

// Setting a cookies into resty
client.SetCookies(cookies)

func (*Client) SetDebug ¶

func (c *Client) SetDebug(d bool) *Client

SetDebug method enables the debug mode on the Resty client. The client logs details of every request and response.

client.SetDebug(true)
// OR
client.EnableDebug()

Also, it can be enabled at the request level for a particular request; see Request.SetDebug.

  • For Request, it logs information such as HTTP verb, Relative URL path, Host, Headers, and Body if it has one.
  • For Response, it logs information such as Status, Response Time, Headers, and Body if it has one.

func (*Client) SetDebugBodyLimit ¶

func (c *Client) SetDebugBodyLimit(sl int) *Client

SetDebugBodyLimit sets the maximum size in bytes for which the response and request body will be logged in debug mode.

client.SetDebugBodyLimit(1000000)

func (*Client) SetDigestAuth ¶

func (c *Client) SetDigestAuth(username, password string) *Client

SetDigestAuth method sets the Digest Auth transport with provided credentials in the client. If a server responds with 401 and sends a Digest challenge in the header `WWW-Authenticate`, the request will be resent with the appropriate digest `Authorization` header.

For Example: To set the Digest scheme with user "Mufasa" and password "Circle Of Life"

client.SetDigestAuth("Mufasa", "Circle Of Life")

Information about Digest Access Authentication can be found in RFC 7616.

NOTE:

  • On the QOP `auth-int` scenario, the request body is read into memory to compute the body hash that consumes additional memory usage.
  • It is recommended to create a dedicated client instance for digest auth, as it does digest auth for all the requests raised by the client.

func (*Client) SetDisableWarn ¶

func (c *Client) SetDisableWarn(d bool) *Client

SetDisableWarn method disables the warning log message on the Resty client.

For example, Resty warns users when BasicAuth is used in non-TLS mode.

client.SetDisableWarn(true)

func (*Client) SetDoNotParseResponse ¶

func (c *Client) SetDoNotParseResponse(notParse bool) *Client

SetDoNotParseResponse method instructs Resty not to parse the response body automatically. Resty exposes the raw response body as io.ReadCloser. If you use it, do not forget to close the body, otherwise, you might get into connection leaks, and connection reuse may not happen.

NOTE: Response middlewares are not executed using this option. You have taken over the control of response parsing from Resty.

func (*Client) SetError ¶

func (c *Client) SetError(v any) *Client

SetError method registers the global or client common `Error` object into Resty. It is used for automatic unmarshalling if the response status code is greater than 399 and content type is JSON or XML. It can be a pointer or a non-pointer.

client.SetError(&Error{})
// OR
client.SetError(Error{})

func (*Client) SetFormData ¶

func (c *Client) SetFormData(data map[string]string) *Client

SetFormData method sets Form parameters and their values in the client instance. It applies only to HTTP methods `POST` and `PUT`, and the request content type would be set as `application/x-www-form-urlencoded`. These form data will be added to all the requests raised from this client instance. Also, it can be overridden at the request level.

See Request.SetFormData.

client.SetFormData(map[string]string{
	"access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
	"user_id": "3455454545",
})

func (*Client) SetGenerateCurlOnDebug ¶

func (c *Client) SetGenerateCurlOnDebug(b bool) *Client

SetGenerateCurlOnDebug method is used to turn on/off the generate CURL command in debug mode at the client instance level. It works in conjunction with debug mode.

NOTE: Use with care.

  • Potential to leak sensitive data from Request and Response in the debug log.
  • Beware of memory usage since the request body is reread.

It can be overridden at the request level; see Request.SetGenerateCurlOnDebug

func (*Client) SetHeader ¶

func (c *Client) SetHeader(header, value string) *Client

SetHeader method sets a single header field and its value in the client instance. These headers will be applied to all requests from this client instance. Also, it can be overridden by request-level header options.

See Request.SetHeader or Request.SetHeaders.

For Example: To set `Content-Type` and `Accept` as `application/json`

client.
	SetHeader("Content-Type", "application/json").
	SetHeader("Accept", "application/json")

func (*Client) SetHeaderVerbatim ¶

func (c *Client) SetHeaderVerbatim(header, value string) *Client

SetHeaderVerbatim method is used to set the HTTP header key and value verbatim in the current request. It is typically helpful for legacy applications or servers that require HTTP headers in a certain way

For Example: To set header key as `all_lowercase`, `UPPERCASE`, and `x-cloud-trace-id`

client.
	SetHeaderVerbatim("all_lowercase", "available").
	SetHeaderVerbatim("UPPERCASE", "available").
	SetHeaderVerbatim("x-cloud-trace-id", "798e94019e5fc4d57fbb8901eb4c6cae")

func (*Client) SetHeaders ¶

func (c *Client) SetHeaders(headers map[string]string) *Client

SetHeaders method sets multiple header fields and their values at one go in the client instance. These headers will be applied to all requests from this client instance. Also, it can be overridden at request level headers options.

See Request.SetHeaders or Request.SetHeader.

For Example: To set `Content-Type` and `Accept` as `application/json`

client.SetHeaders(map[string]string{
	"Content-Type": "application/json",
	"Accept": "application/json",
})

func (*Client) SetJSONEscapeHTML ¶

func (c *Client) SetJSONEscapeHTML(b bool) *Client

SetJSONEscapeHTML method enables or disables the HTML escape on JSON marshal. By default, escape HTML is `true`.

NOTE: This option only applies to the standard JSON Marshaller used by Resty.

It can be overridden at the request level, see Request.SetJSONEscapeHTML

func (*Client) SetLoadBalancer ¶

func (c *Client) SetLoadBalancer(b LoadBalancer) *Client

SetLoadBalancer method is used to set the new request load balancer into the client.

func (*Client) SetLogger ¶

func (c *Client) SetLogger(l Logger) *Client

SetLogger method sets given writer for logging Resty request and response details.

Compliant to interface resty.Logger

func (*Client) SetOutputDirectory ¶

func (c *Client) SetOutputDirectory(dirPath string) *Client

SetOutputDirectory method sets the output directory for saving HTTP responses in a file. Resty creates one if the output directory does not exist. This setting is optional, if you plan to use the absolute path in Request.SetOutputFile and can used together.

client.SetOutputDirectory("/save/http/response/here")

func (*Client) SetPathParam ¶

func (c *Client) SetPathParam(param, value string) *Client

SetPathParam method sets a single URL path key-value pair in the Resty client instance.

client.SetPathParam("userId", "sample@sample.com")

Result:
   URL - /v1/users/{userId}/details
   Composed URL - /v1/users/sample@sample.com/details

It replaces the value of the key while composing the request URL. The value will be escaped using url.PathEscape function.

It can be overridden at the request level, see Request.SetPathParam or Request.SetPathParams

func (*Client) SetPathParams ¶

func (c *Client) SetPathParams(params map[string]string) *Client

SetPathParams method sets multiple URL path key-value pairs at one go in the Resty client instance.

client.SetPathParams(map[string]string{
	"userId":       "sample@sample.com",
	"subAccountId": "100002",
	"path":         "groups/developers",
})

Result:
   URL - /v1/users/{userId}/{subAccountId}/{path}/details
   Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details

It replaces the value of the key while composing the request URL. The values will be escaped using url.PathEscape function.

It can be overridden at the request level, see Request.SetPathParam or Request.SetPathParams

func (*Client) SetProxy ¶

func (c *Client) SetProxy(proxyURL string) *Client

SetProxy method sets the Proxy URL and Port for the Resty client.

client.SetProxy("http://proxyserver:8888")

OR you could also set Proxy via environment variable, refer to http.ProxyFromEnvironment

func (*Client) SetQueryParam ¶

func (c *Client) SetQueryParam(param, value string) *Client

SetQueryParam method sets a single parameter and its value in the client instance. It will be formed as a query string for the request.

For Example: `search=kitchen%20papers&size=large`

In the URL after the `?` mark. These query params will be added to all the requests raised from this client instance. Also, it can be overridden at the request level.

See Request.SetQueryParam or Request.SetQueryParams.

client.
	SetQueryParam("search", "kitchen papers").
	SetQueryParam("size", "large")

func (*Client) SetQueryParams ¶

func (c *Client) SetQueryParams(params map[string]string) *Client

SetQueryParams method sets multiple parameters and their values at one go in the client instance. It will be formed as a query string for the request.

For Example: `search=kitchen%20papers&size=large`

In the URL after the `?` mark. These query params will be added to all the requests raised from this client instance. Also, it can be overridden at the request level.

See Request.SetQueryParams or Request.SetQueryParam.

client.SetQueryParams(map[string]string{
	"search": "kitchen papers",
	"size": "large",
})

func (*Client) SetRawPathParam ¶

func (c *Client) SetRawPathParam(param, value string) *Client

SetRawPathParam method sets a single URL path key-value pair in the Resty client instance.

client.SetPathParam("userId", "sample@sample.com")

Result:
   URL - /v1/users/{userId}/details
   Composed URL - /v1/users/sample@sample.com/details

client.SetPathParam("path", "groups/developers")

Result:
   URL - /v1/users/{userId}/details
   Composed URL - /v1/users/groups%2Fdevelopers/details

It replaces the value of the key while composing the request URL. The value will be used as it is and will not be escaped.

It can be overridden at the request level, see Request.SetRawPathParam or Request.SetRawPathParams

func (*Client) SetRawPathParams ¶

func (c *Client) SetRawPathParams(params map[string]string) *Client

SetRawPathParams method sets multiple URL path key-value pairs at one go in the Resty client instance.

client.SetPathParams(map[string]string{
	"userId":       "sample@sample.com",
	"subAccountId": "100002",
	"path":         "groups/developers",
})

Result:
   URL - /v1/users/{userId}/{subAccountId}/{path}/details
   Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details

It replaces the value of the key while composing the request URL. The values will be used as they are and will not be escaped.

It can be overridden at the request level, see Request.SetRawPathParam or Request.SetRawPathParams

func (*Client) SetRedirectPolicy ¶

func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client

SetRedirectPolicy method sets the redirect policy for the client. Resty provides ready-to-use redirect policies. Wanna create one for yourself, refer to `redirect.go`.

client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))

// Need multiple redirect policies together
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20), resty.DomainCheckRedirectPolicy("host1.com", "host2.net"))

NOTE: It overwrites the previous redirect policies in the client instance.

func (*Client) SetRequestMiddlewares ¶

func (c *Client) SetRequestMiddlewares(middlewares ...RequestMiddleware) *Client

SetRequestMiddlewares method allows Resty users to override the default request middlewares sequence

client := New()
defer client.Close()

client.SetRequestMiddlewares(
	CustomRequest1Middleware,
	CustomRequest2Middleware,
	resty.PrepareRequestMiddleware, // after this, Request.RawRequest is available
	resty.GenerateCurlRequestMiddleware,
	CustomRequest3Middleware,
	CustomRequest4Middleware,
)

See, Client.AddRequestMiddleware

NOTE:

  • It overwrites the existing request middleware list.
  • Be sure to include Resty request middlewares in the request chain at the appropriate spot.

func (*Client) SetResponseBodyLimit ¶

func (c *Client) SetResponseBodyLimit(v int64) *Client

SetResponseBodyLimit method sets a maximum body size limit in bytes on response, avoid reading too much data to memory.

Client will return resty.ErrResponseBodyTooLarge if the body size of the body in the uncompressed response is larger than the limit. Body size limit will not be enforced in the following cases:

  • ResponseBodyLimit <= 0, which is the default behavior.
  • Request.SetOutputFile is called to save response data to the file.
  • "DoNotParseResponse" is set for client or request.

It can be overridden at the request level; see Request.SetResponseBodyLimit

func (*Client) SetResponseBodyUnlimitedReads ¶

func (c *Client) SetResponseBodyUnlimitedReads(b bool) *Client

SetResponseBodyUnlimitedReads method is to turn on/off the response body copy that provides an ability to do unlimited reads.

It can be overridden at the request level; see Request.SetResponseBodyUnlimitedReads

Unlimited reads are possible in a few scenarios, even without enabling it.

  • When debug mode is enabled

NOTE: Use with care

  • Turning on this feature uses additional memory to store a copy of the response body buffer.

func (*Client) SetResponseMiddlewares ¶

func (c *Client) SetResponseMiddlewares(middlewares ...ResponseMiddleware) *Client

SetResponseMiddlewares method allows Resty users to override the default response middlewares sequence

client := New()
defer client.Close()

client.SetResponseMiddlewares(
	CustomResponse1Middleware,
	CustomResponse2Middleware,
	resty.AutoParseResponseMiddleware, // before this, body is not read except on debug flow
	CustomResponse3Middleware,
	resty.SaveToFileResponseMiddleware, // See, Request.SetOutputFile
	CustomResponse4Middleware,
	CustomResponse5Middleware,
)

See, Client.AddResponseMiddleware

NOTE:

  • It overwrites the existing request middleware list.
  • Be sure to include Resty response middlewares in the response chain at the appropriate spot.

func (*Client) SetRetryCount ¶

func (c *Client) SetRetryCount(count int) *Client

SetRetryCount method enables retry on Resty client and allows you to set no. of retry count.

first attempt + retry count = total attempts

See Request.SetRetryStrategy

NOTE:

func (*Client) SetRetryDefaultConditions ¶

func (c *Client) SetRetryDefaultConditions(b bool) *Client

SetRetryDefaultConditions method is used to enable/disable the Resty's default retry conditions

It can be overridden at request level, see Request.SetRetryDefaultConditions

func (*Client) SetRetryMaxWaitTime ¶

func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client

SetRetryMaxWaitTime method sets the max wait time for sleep before retrying

Default is 2 seconds.

func (*Client) SetRetryStrategy ¶

func (c *Client) SetRetryStrategy(rs RetryStrategyFunc) *Client

SetRetryStrategy method used to set the custom Retry strategy into Resty client, it is used to get wait time before each retry. It can be overridden at request level, see Request.SetRetryStrategy

Default (nil) implies exponential backoff with a jitter strategy

func (*Client) SetRetryWaitTime ¶

func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client

SetRetryWaitTime method sets the default wait time for sleep before retrying

Default is 100 milliseconds.

func (*Client) SetRootCertificate ¶

func (c *Client) SetRootCertificate(pemFilePath string) *Client

SetRootCertificate method helps to add one or more root certificates into the Resty client

client.SetRootCertificate("/path/to/root/pemFile.pem")

func (*Client) SetRootCertificateFromString ¶

func (c *Client) SetRootCertificateFromString(pemCerts string) *Client

SetRootCertificateFromString method helps to add one or more root certificates into the Resty client

client.SetRootCertificateFromString("pem certs content")

func (*Client) SetRootCertificateWatcher ¶

func (c *Client) SetRootCertificateWatcher(pemFilePath string, options *CertWatcherOptions) *Client

SetRootCertificateWatcher enables dynamic reloading of one or more root certificates. It is designed for scenarios involving long-running Resty clients where certificates may be renewed. The caller is responsible for calling Close to stop the watcher.

client.SetRootCertificateWatcher("root-ca.crt", &CertWatcherOptions{
	PoolInterval: time.Hour * 24,
})

defer client.Close()

func (*Client) SetScheme ¶

func (c *Client) SetScheme(scheme string) *Client

SetScheme method sets a custom scheme for the Resty client. It's a way to override the default.

client.SetScheme("http")

func (*Client) SetTLSClientConfig ¶

func (c *Client) SetTLSClientConfig(tlsConfig *tls.Config) *Client

SetTLSClientConfig method sets TLSClientConfig for underlying client Transport.

For Example:

// One can set a custom root certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial
client.SetTLSClientConfig(&tls.Config{ RootCAs: roots })

// or One can disable security check (https)
client.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })

NOTE: This method overwrites existing http.Transport.TLSClientConfig

func (*Client) SetTimeout ¶

func (c *Client) SetTimeout(timeout time.Duration) *Client

SetTimeout method is used to set a timeout for a request raised by the client.

client.SetTimeout(1 * time.Minute)

It can be overridden at the request level. See Request.SetTimeout

NOTE: Resty uses context.WithTimeout on the request, it does not use http.Client.Timeout

func (*Client) SetTrace ¶

func (c *Client) SetTrace(t bool) *Client

SetTrace method is used to turn on/off the trace capability in the Resty client Refer to Client.EnableTrace or Client.DisableTrace.

Also, see Request.SetTrace

func (*Client) SetTransport ¶

func (c *Client) SetTransport(transport http.RoundTripper) *Client

SetTransport method sets custom http.Transport or any http.RoundTripper compatible interface implementation in the Resty client.

transport := &http.Transport{
	// something like Proxying to httptest.Server, etc...
	Proxy: func(req *http.Request) (*url.URL, error) {
		return url.Parse(server.URL)
	},
}
client.SetTransport(transport)

NOTE:

  • If transport is not the type of http.Transport, you may lose the ability to set a few Resty client settings. However, if you implement TLSClientConfiger interface, then TLS client config is possible to set.
  • It overwrites the Resty client transport instance and its configurations.

func (*Client) SetUnescapeQueryParams ¶

func (c *Client) SetUnescapeQueryParams(unescape bool) *Client

SetUnescapeQueryParams method sets the choice of unescape query parameters for the request URL. To prevent broken URL, Resty replaces space (" ") with "+" in the query parameters.

See Request.SetUnescapeQueryParams

NOTE: Request failure is possible due to non-standard usage of Unescaped Query Parameters.

func (*Client) TLSClientConfig ¶

func (c *Client) TLSClientConfig() *tls.Config

TLSClientConfig method returns the tls.Config from underlying client transport otherwise returns nil

func (*Client) Timeout ¶

func (c *Client) Timeout() time.Duration

Timeout method returns the timeout duration value from the client

func (*Client) Transport ¶

func (c *Client) Transport() http.RoundTripper

Transport method returns underlying client transport referance as-is i.e., http.RoundTripper

type ContentDecompressor ¶

type ContentDecompressor func(io.ReadCloser) (io.ReadCloser, error)

ContentDecompressor type is for decompressing response body based on header Content-Encoding (RFC 9110)

For example, gzip, deflate, etc.

type ContentTypeDecoder ¶

type ContentTypeDecoder func(io.Reader, any) error

ContentTypeDecoder type is for decoding the response body based on header Content-Type

type ContentTypeEncoder ¶

type ContentTypeEncoder func(io.Writer, any) error

ContentTypeEncoder type is for encoding the request body based on header Content-Type

type DebugLog ¶

type DebugLog struct {
	Header http.Header
	Body   string
}

DebugLog struct is used to collect details from Resty request and response for debug logging callback purposes.

type DebugLogCallback ¶

type DebugLogCallback func(*DebugLog)

DebugLogCallback type is for request and response debug log callback purpose. It gets called before Resty logs it

type ErrorHook ¶

type ErrorHook func(*Request, error)

ErrorHook type is for reacting to request errors, called after all retries were attempted

type Host ¶

type Host struct {
	// BaseURL represents the targeted host base URL
	//	https://resty.dev
	BaseURL string

	// Weight represents the host weight to determine
	// the percentage of requests to send
	Weight int

	// MaxFailures represents the value to mark the host as
	// not usable until it reaches the Recovery duration
	//	Default value is 5
	MaxFailures int
	// contains filtered or unexported fields
}

Host struct used to represent the host information and its weight to load balance the requests

type HostStateChangeFunc ¶

type HostStateChangeFunc func(baseURL string, from, to State)

HostStateChangeFunc type provides feedback on host state transitions

type LoadBalancer ¶

type LoadBalancer interface {
	Next() (string, error)
	Feedback(*RequestFeedback)
	Close() error
}

LoadBalancer is the interface that wraps the HTTP client load-balancing algorithm that returns the "Next" Base URL for the request to target

type Logger ¶

type Logger interface {
	Errorf(format string, v ...any)
	Warnf(format string, v ...any)
	Debugf(format string, v ...any)
}

Logger interface is to abstract the logging from Resty. Gives control to the Resty users, choice of the logger.

type MultipartField ¶

type MultipartField struct {
	// Name of the multipart field name that the server expects it
	Name string

	// FileName is used to set the file name we have to send to the server
	FileName string

	// ContentType is a multipart file content-type value. It is highly
	// recommended setting it if you know the content-type so that Resty
	// don't have to do additional computing to auto-detect (Optional)
	ContentType string

	// Reader is an input of [io.Reader] for multipart upload. It
	// is optional if you set the FilePath value
	Reader io.Reader

	// FilePath is a file path for multipart upload. It
	// is optional if you set the Reader value
	FilePath string

	// FileSize in bytes is used just for the information purpose of
	// sharing via [MultipartFieldCallbackFunc] (Optional)
	FileSize int64

	// ProgressCallback function is used to provide live progress details
	// during a multipart upload (Optional)
	//
	// NOTE: It is recommended to set the FileSize value when using
	// ProgressCallback feature so that Resty sends the FileSize
	// value via [MultipartFieldProgress]
	ProgressCallback MultipartFieldCallbackFunc

	// Values field is used to provide form field value. (Optional, unless it's a form-data field)
	//
	// It is primarily added for ordered multipart form-data field use cases
	Values []string
}

MultipartField struct represents the multipart field to compose all io.Reader capable input for multipart form request

func (*MultipartField) Clone ¶

func (mf *MultipartField) Clone() *MultipartField

Clone method returns the deep copy of m except io.Reader.

type MultipartFieldCallbackFunc ¶

type MultipartFieldCallbackFunc func(MultipartFieldProgress)

MultipartFieldCallbackFunc function used to transmit live multipart upload progress in bytes count

type MultipartFieldProgress ¶

type MultipartFieldProgress struct {
	Name     string
	FileName string
	FileSize int64
	Written  int64
}

MultipartFieldProgress struct used to provide multipart field upload progress details via callback function

func (MultipartFieldProgress) String ¶

func (mfp MultipartFieldProgress) String() string

String method creates the string representation of MultipartFieldProgress

type RedirectPolicy ¶

type RedirectPolicy interface {
	Apply(*http.Request, []*http.Request) error
}

RedirectPolicy to regulate the redirects in the Resty client. Objects implementing the RedirectPolicy interface can be registered as

Apply function should return nil to continue the redirect journey; otherwise return error to stop the redirect.

func DomainCheckRedirectPolicy ¶

func DomainCheckRedirectPolicy(hostnames ...string) RedirectPolicy

DomainCheckRedirectPolicy method is convenient for defining domain name redirect rules in Resty clients. Redirect is allowed only for the host mentioned in the policy.

resty.SetRedirectPolicy(resty.DomainCheckRedirectPolicy("host1.com", "host2.org", "host3.net"))

func FlexibleRedirectPolicy ¶

func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy

FlexibleRedirectPolicy method is convenient for creating several redirect policies for Resty clients.

resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))

func NoRedirectPolicy ¶

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy is used to disable the redirects in the Resty client

resty.SetRedirectPolicy(resty.NoRedirectPolicy())

type RedirectPolicyFunc ¶

type RedirectPolicyFunc func(*http.Request, []*http.Request) error

The RedirectPolicyFunc type is an adapter to allow the use of ordinary functions as RedirectPolicy. If `f` is a function with the appropriate signature, RedirectPolicyFunc(f) is a RedirectPolicy object that calls `f`.

func (RedirectPolicyFunc) Apply ¶

func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error

Apply calls f(req, via).

type Request ¶

type Request struct {
	URL                        string
	Method                     string
	AuthToken                  string
	AuthScheme                 string
	QueryParams                url.Values
	FormData                   url.Values
	PathParams                 map[string]string
	RawPathParams              map[string]string
	Header                     http.Header
	Time                       time.Time
	Body                       any
	Result                     any
	Error                      any
	RawRequest                 *http.Request
	Cookies                    []*http.Cookie
	Debug                      bool
	CloseConnection            bool
	DoNotParseResponse         bool
	OutputFile                 string
	ExpectResponseContentType  string
	ForceResponseContentType   string
	DebugBodyLimit             int
	ResponseBodyLimit          int64
	ResponseBodyUnlimitedReads bool
	IsTrace                    bool
	AllowMethodGetPayload      bool
	AllowMethodDeletePayload   bool
	IsDone                     bool
	Timeout                    time.Duration
	RetryCount                 int
	RetryWaitTime              time.Duration
	RetryMaxWaitTime           time.Duration
	RetryStrategy              RetryStrategyFunc
	IsRetryDefaultConditions   bool
	AllowNonIdempotentRetry    bool

	// RetryTraceID provides GUID for retry count > 0
	RetryTraceID string

	// Attempt provides insights into no. of attempts
	// Resty made.
	//
	//	first attempt + retry count = total attempts
	Attempt int
	// contains filtered or unexported fields
}

Request struct is used to compose and fire individual requests from Resty client. The Request provides an option to override client-level settings and also an option for the request composition.

func (*Request) AddRetryCondition ¶

func (r *Request) AddRetryCondition(condition RetryConditionFunc) *Request

AddRetryCondition method adds a retry condition function to the request's array of functions is checked to determine if the request can be retried. The request will retry if any functions return true and the error is nil.

NOTE: The request level retry conditions are checked before all retry conditions from the client instance.

func (*Request) Clone ¶

func (r *Request) Clone(ctx context.Context) *Request

Clone returns a deep copy of r with its context changed to ctx. It does clone appropriate fields, reset, and reinitialize, so Request can be used again.

The body is not copied, but it's a reference to the original body.

req := client.R().
	SetBody("body").
	SetHeader("header", "value")
clonedRequest := req.Clone(context.Background())

func (*Request) Context ¶

func (r *Request) Context() context.Context

Context method returns the request's context.Context. To change the context, use Request.Clone or Request.WithContext.

The returned context is always non-nil; it defaults to the background context.

func (*Request) Delete ¶

func (r *Request) Delete(url string) (*Response, error)

Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231.

func (*Request) DisableDebug ¶

func (r *Request) DisableDebug() *Request

DisableDebug method is a helper method for Request.SetDebug

func (*Request) DisableGenerateCurlOnDebug ¶

func (r *Request) DisableGenerateCurlOnDebug() *Request

DisableGenerateCurlOnDebug method disables the option set by Request.EnableGenerateCurlOnDebug. It overrides the options set by the Client.

func (*Request) DisableRetryDefaultConditions ¶

func (r *Request) DisableRetryDefaultConditions() *Request

DisableRetryDefaultConditions method disables the Resty's default retry conditions on request level

func (*Request) DisableTrace ¶

func (r *Request) DisableTrace() *Request

DisableTrace method disables the request trace for the current request

func (*Request) EnableDebug ¶

func (r *Request) EnableDebug() *Request

EnableDebug method is a helper method for Request.SetDebug

func (*Request) EnableGenerateCurlOnDebug ¶

func (r *Request) EnableGenerateCurlOnDebug() *Request

EnableGenerateCurlOnDebug method enables the generation of CURL commands in the debug log. It works in conjunction with debug mode. It overrides the options set by the Client.

NOTE: Use with care.

  • Potential to leak sensitive data from Request and Response in the debug log.
  • Beware of memory usage since the request body is reread.

func (*Request) EnableRetryDefaultConditions ¶

func (r *Request) EnableRetryDefaultConditions() *Request

EnableRetryDefaultConditions method enables the Resty's default retry conditions on request level

func (*Request) EnableTrace ¶

func (r *Request) EnableTrace() *Request

EnableTrace method enables trace for the current request using httptrace.ClientTrace and provides insights.

client := resty.New()

resp, err := client.R().EnableTrace().Get("https://httpbin.org/get")
fmt.Println("Error:", err)
fmt.Println("Trace Info:", resp.Request.TraceInfo())

See Client.EnableTrace, Client.SetTrace are also available to get trace info for all requests.

func (*Request) Execute ¶

func (r *Request) Execute(method, url string) (res *Response, err error)

Execute method performs the HTTP request with the given HTTP method and URL for current Request.

resp, err := client.R().Execute(resty.MethodGet, "http://httpbin.org/get")

func (*Request) Funcs ¶

func (r *Request) Funcs(funcs ...RequestFunc) *Request

Funcs method gets executed on request composition that passes the current request instance to provided RequestFunc, which could be used to apply common/reusable logic to the given request instance.

func addRequestContentType(r *Request) *Request {
	return r.SetHeader("Content-Type", "application/json").
		SetHeader("Accept", "application/json")
}

func addRequestQueryParams(page, size int) func(r *Request) *Request {
	return func(r *Request) *Request {
		return r.SetQueryParam("page", strconv.Itoa(page)).
			SetQueryParam("size", strconv.Itoa(size)).
			SetQueryParam("request_no", strconv.Itoa(int(time.Now().Unix())))
	}
}

client.R().
	Funcs(addRequestContentType, addRequestQueryParams(1, 100)).
	Get("https://localhost:8080/foobar")

func (*Request) GenerateCurlCommand ¶

func (r *Request) GenerateCurlCommand() string

GenerateCurlCommand method generates the CURL command for the request.

func (*Request) Get ¶

func (r *Request) Get(url string) (*Response, error)

Get method does GET HTTP request. It's defined in section 4.3.1 of RFC7231.

func (*Request) Head ¶

func (r *Request) Head(url string) (*Response, error)

Head method does HEAD HTTP request. It's defined in section 4.3.2 of RFC7231.

func (*Request) Options ¶

func (r *Request) Options(url string) (*Response, error)

Options method does OPTIONS HTTP request. It's defined in section 4.3.7 of RFC7231.

func (*Request) Patch ¶

func (r *Request) Patch(url string) (*Response, error)

Patch method does PATCH HTTP request. It's defined in section 2 of RFC5789.

func (*Request) Post ¶

func (r *Request) Post(url string) (*Response, error)

Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231.

func (*Request) Put ¶

func (r *Request) Put(url string) (*Response, error)

Put method does PUT HTTP request. It's defined in section 4.3.4 of RFC7231.

func (*Request) Send ¶

func (r *Request) Send() (*Response, error)

Send method performs the HTTP request using the method and URL already defined for current Request.

res, err := client.R().
	SetMethod(resty.MethodGet).
	SetURL("http://httpbin.org/get").
	Send()

func (*Request) SetAllowMethodDeletePayload ¶

func (r *Request) SetAllowMethodDeletePayload(allow bool) *Request

SetAllowMethodDeletePayload method allows the DELETE method with payload on the request level. By default, Resty does not allow.

client.R().SetAllowMethodDeletePayload(true)

More info, refer to GH#881

It overrides the option set by the Client.SetAllowMethodDeletePayload

func (*Request) SetAllowMethodGetPayload ¶

func (r *Request) SetAllowMethodGetPayload(allow bool) *Request

SetAllowMethodGetPayload method allows the GET method with payload on the request level. By default, Resty does not allow.

client.R().SetAllowMethodGetPayload(true)

It overrides the option set by the Client.SetAllowMethodGetPayload

func (*Request) SetAllowNonIdempotentRetry ¶

func (r *Request) SetAllowNonIdempotentRetry(b bool) *Request

SetAllowNonIdempotentRetry method is used to enable/disable non-idempotent HTTP methods retry. By default, Resty only allows idempotent HTTP methods, see RFC 9110 Section 9.2.2, RFC 9110 Section 18.2

It overrides value set at the client instance level, see Client.SetAllowNonIdempotentRetry

func (*Request) SetAuthScheme ¶

func (r *Request) SetAuthScheme(scheme string) *Request

SetAuthScheme method sets the auth token scheme type in the HTTP request.

Example Header value structure:

Authorization: <auth-scheme-value-set-here> <auth-token-value>

For Example: To set the scheme to use OAuth

client.R().SetAuthScheme("OAuth")

// The outcome will be -
Authorization: OAuth <auth-token-value>

Information about Auth schemes can be found in RFC 7235, IANA HTTP Auth schemes

It overrides the `Authorization` scheme set by method Client.SetAuthScheme.

func (*Request) SetAuthToken ¶

func (r *Request) SetAuthToken(authToken string) *Request

SetAuthToken method sets the auth token header(Default Scheme: Bearer) in the current HTTP request. Header example:

Authorization: Bearer <auth-token-value-comes-here>

For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F

client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")

It overrides the Auth token set by method Client.SetAuthToken.

func (*Request) SetBasicAuth ¶

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth method sets the basic authentication header in the current HTTP request.

For Example:

Authorization: Basic <base64-encoded-value>

To set the header for username "go-resty" and password "welcome"

client.R().SetBasicAuth("go-resty", "welcome")

It overrides the credentials set by method Client.SetBasicAuth.

func (*Request) SetBody ¶

func (r *Request) SetBody(body any) *Request

SetBody method sets the request body for the request. It supports various practical needs as easy. It's quite handy and powerful. Supported request body data types are `string`, `[]byte`, `struct`, `map`, `slice` and io.Reader.

Body value can be pointer or non-pointer. Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`.

NOTE: io.Reader is processed in bufferless mode while sending a request.

For Example:

`struct` gets marshaled based on the request header `Content-Type`.

client.R().
	SetBody(User{
		Username: "jeeva@myjeeva.com",
		Password: "welcome2resty",
	})

'map` gets marshaled based on the request header `Content-Type`.

client.R().
	SetBody(map[string]any{
		"username": "jeeva@myjeeva.com",
		"password": "welcome2resty",
		"address": &Address{
			Address1: "1111 This is my street",
			Address2: "Apt 201",
			City: "My City",
			State: "My State",
			ZipCode: 00000,
		},
	})

`string` as a body input. Suitable for any need as a string input.

client.R().
	SetBody(`{
		"username": "jeeva@getrightcare.com",
		"password": "admin"
	}`)

`[]byte` as a body input. Suitable for raw requests such as file upload, serialize & deserialize, etc.

client.R().
	SetBody([]byte("This is my raw request, sent as-is"))

and so on.

func (*Request) SetCloseConnection ¶

func (r *Request) SetCloseConnection(close bool) *Request

SetCloseConnection method sets variable `Close` in HTTP request struct with the given value. More info: https://golang.org/src/net/http/request.go

It overrides the value set at the client instance level, see Client.SetCloseConnection

func (*Request) SetContentLength ¶

func (r *Request) SetContentLength(l bool) *Request

SetContentLength method sets the current request's HTTP header `Content-Length` value. By default, Resty won't set `Content-Length`.

See Client.SetContentLength

client.R().SetContentLength(true)

It overrides the value set at the client instance level.

func (*Request) SetContext ¶

func (r *Request) SetContext(ctx context.Context) *Request

SetContext method sets the context.Context for current Request. It overwrites the current context in the Request instance; it does not affect the Request.RawRequest that was already created.

If you want this method to take effect, use this method before invoking Request.Send or Request.HTTPVerb methods.

See Request.WithContext, Request.Clone

func (*Request) SetCookie ¶

func (r *Request) SetCookie(hc *http.Cookie) *Request

SetCookie method appends a single cookie in the current request instance.

client.R().SetCookie(&http.Cookie{
			Name:"go-resty",
			Value:"This is cookie value",
		})

NOTE: Method appends the Cookie value into existing Cookie even if its already existing.

func (*Request) SetCookies ¶

func (r *Request) SetCookies(rs []*http.Cookie) *Request

SetCookies method sets an array of cookies in the current request instance.

cookies := []*http.Cookie{
	&http.Cookie{
		Name:"go-resty-1",
		Value:"This is cookie 1 value",
	},
	&http.Cookie{
		Name:"go-resty-2",
		Value:"This is cookie 2 value",
	},
}

// Setting a cookies into resty's current request
client.R().SetCookies(cookies)

NOTE: Method appends the Cookie value into existing Cookie even if its already existing.

func (*Request) SetDebug ¶

func (r *Request) SetDebug(d bool) *Request

SetDebug method enables the debug mode on the current request. It logs the details current request and response.

client.R().SetDebug(true)
// OR
client.R().EnableDebug()

Also, it can be enabled at the request level for a particular request; see Request.SetDebug.

  • For Request, it logs information such as HTTP verb, Relative URL path, Host, Headers, and Body if it has one.
  • For Response, it logs information such as Status, Response Time, Headers, and Body if it has one.

func (*Request) SetDoNotParseResponse ¶

func (r *Request) SetDoNotParseResponse(notParse bool) *Request

SetDoNotParseResponse method instructs Resty not to parse the response body automatically. Resty exposes the raw response body as io.ReadCloser. If you use it, do not forget to close the body, otherwise, you might get into connection leaks, and connection reuse may not happen.

NOTE: Response middlewares are not executed using this option. You have taken over the control of response parsing from Resty.

func (*Request) SetError ¶

func (r *Request) SetError(err any) *Request

SetError method is to register the request `Error` object for automatic unmarshalling for the request, if the response status code is greater than 399 and the content type is either JSON or XML.

NOTE: Request.SetError input can be a pointer or non-pointer.

client.R().SetError(&AuthError{})
// OR
client.R().SetError(AuthError{})

Accessing an error value from response instance.

response.Error().(*AuthError)

If this request Error object is nil, Resty will use the client-level error object Type if it is set.

func (*Request) SetExpectResponseContentType ¶

func (r *Request) SetExpectResponseContentType(contentType string) *Request

SetExpectResponseContentType method allows to provide fallback `Content-Type` for automatic unmarshalling when the `Content-Type` response header is unavailable.

func (*Request) SetFile ¶

func (r *Request) SetFile(fieldName, filePath string) *Request

SetFile method sets a single file field name and its path for multipart upload.

Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields

client.R().
	SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf")

func (*Request) SetFileReader ¶

func (r *Request) SetFileReader(fieldName, fileName string, reader io.Reader) *Request

SetFileReader method is to set a file using io.Reader for multipart upload.

Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields

client.R().
	SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)).
	SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes))

func (*Request) SetFiles ¶

func (r *Request) SetFiles(files map[string]string) *Request

SetFiles method sets multiple file field names and their paths for multipart uploads.

Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields

client.R().
	SetFiles(map[string]string{
		"my_file1": "/Users/jeeva/Gas Bill - Sep.pdf",
		"my_file2": "/Users/jeeva/Electricity Bill - Sep.pdf",
		"my_file3": "/Users/jeeva/Water Bill - Sep.pdf",
	})

func (*Request) SetForceResponseContentType ¶

func (r *Request) SetForceResponseContentType(contentType string) *Request

SetForceResponseContentType method provides a strong sense of response `Content-Type` for automatic unmarshalling. Resty gives this a higher priority than the `Content-Type` response header.

This means that if both Request.SetForceResponseContentType is set and the response `Content-Type` is available, `SetForceResponseContentType` value will win.

func (*Request) SetFormData ¶

func (r *Request) SetFormData(data map[string]string) *Request

SetFormData method sets Form parameters and their values for the current request. It applies only to HTTP methods `POST` and `PUT`, and by default requests content type would be set as `application/x-www-form-urlencoded`.

client.R().
	SetFormData(map[string]string{
		"access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
		"user_id": "3455454545",
	})

It overrides the form data value set at the client instance level.

See Request.SetFormDataFromValues for the same field name with multiple values.

func (*Request) SetFormDataFromValues ¶

func (r *Request) SetFormDataFromValues(data url.Values) *Request

SetFormDataFromValues method appends multiple form parameters with multi-value (url.Values) at one go in the current request.

client.R().
	SetFormDataFromValues(url.Values{
		"search_criteria": []string{"book", "glass", "pencil"},
	})

It overrides the form data value set at the client instance level.

func (*Request) SetGenerateCurlOnDebug ¶

func (r *Request) SetGenerateCurlOnDebug(b bool) *Request

SetGenerateCurlOnDebug method is used to turn on/off the generate CURL command in debug mode. It works in conjunction with debug mode.

NOTE: Use with care.

  • Potential to leak sensitive data from Request and Response in the debug log.
  • Beware of memory usage since the request body is reread.

It overrides the options set by the Client.SetGenerateCurlOnDebug

func (*Request) SetHeader ¶

func (r *Request) SetHeader(header, value string) *Request

SetHeader method sets a single header field and its value in the current request.

For Example: To set `Content-Type` and `Accept` as `application/json`.

client.R().
	SetHeader("Content-Type", "application/json").
	SetHeader("Accept", "application/json")

It overrides the header value set at the client instance level.

func (*Request) SetHeaderMultiValues ¶

func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request

SetHeaderMultiValues sets multiple header fields and their values as a list of strings in the current request.

For Example: To set `Accept` as `text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8`

client.R().
	SetHeaderMultiValues(map[string][]string{
		"Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"},
	})

It overrides the header value set at the client instance level.

func (*Request) SetHeaderVerbatim ¶

func (r *Request) SetHeaderVerbatim(header, value string) *Request

SetHeaderVerbatim method is used to set the HTTP header key and value verbatim in the current request. It is typically helpful for legacy applications or servers that require HTTP headers in a certain way

For Example: To set header key as `all_lowercase`, `UPPERCASE`, and `x-cloud-trace-id`

client.R().
	SetHeaderVerbatim("all_lowercase", "available").
	SetHeaderVerbatim("UPPERCASE", "available").
	SetHeaderVerbatim("x-cloud-trace-id", "798e94019e5fc4d57fbb8901eb4c6cae")

It overrides the header value set at the client instance level.

func (*Request) SetHeaders ¶

func (r *Request) SetHeaders(headers map[string]string) *Request

SetHeaders method sets multiple header fields and their values at one go in the current request.

For Example: To set `Content-Type` and `Accept` as `application/json`

client.R().
	SetHeaders(map[string]string{
		"Content-Type": "application/json",
		"Accept": "application/json",
	})

It overrides the header value set at the client instance level.

func (*Request) SetJSONEscapeHTML ¶

func (r *Request) SetJSONEscapeHTML(b bool) *Request

SetJSONEscapeHTML method enables or disables the HTML escape on JSON marshal. By default, escape HTML is `true`.

NOTE: This option only applies to the standard JSON Marshaller used by Resty.

It overrides the value set at the client instance level, see Client.SetJSONEscapeHTML

func (*Request) SetLogger ¶

func (r *Request) SetLogger(l Logger) *Request

SetLogger method sets given writer for logging Resty request and response details. By default, requests and responses inherit their logger from the client.

Compliant to interface resty.Logger.

It overrides the logger value set at the client instance level.

func (*Request) SetMethod ¶

func (r *Request) SetMethod(m string) *Request

SetMethod method used to set the HTTP verb for the request

func (*Request) SetMultipartBoundary ¶

func (r *Request) SetMultipartBoundary(boundary string) *Request

SetMultipartBoundary method sets the custom multipart boundary for the multipart request. Typically, the `mime/multipart` package generates a random multipart boundary if not provided.

func (*Request) SetMultipartField ¶

func (r *Request) SetMultipartField(fieldName, fileName, contentType string, reader io.Reader) *Request

SetMultipartField method sets custom data with Content-Type using io.Reader for multipart upload.

Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields

func (*Request) SetMultipartFields ¶

func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request

SetMultipartFields method sets multiple data fields using io.Reader for multipart upload.

Resty provides an optional multipart live upload progress count in bytes; see MultipartField.ProgressCallback and MultipartFieldProgress

For Example:

client.R().SetMultipartFields(
	&resty.MultipartField{
		Name:        "uploadManifest1",
		FileName:    "upload-file-1.json",
		ContentType: "application/json",
		Reader:      strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`),
	},
	&resty.MultipartField{
		Name:        "uploadManifest2",
		FileName:    "upload-file-2.json",
		ContentType: "application/json",
		FilePath:    "/path/to/upload-file-2.json",
	},
	&resty.MultipartField{
		Name:             "image-file1",
		FileName:         "image-file1.png",
		ContentType:      "image/png",
		Reader:           bytes.NewReader(fileBytes),
		ProgressCallback: func(mp MultipartFieldProgress) {
			// use the progress details
		},
	},
	&resty.MultipartField{
		Name:             "image-file2",
		FileName:         "image-file2.png",
		ContentType:      "image/png",
		Reader:           imageFile2, // instance of *os.File
		ProgressCallback: func(mp MultipartFieldProgress) {
			// use the progress details
		},
	})

If you have a `slice` of fields already, then call-

client.R().SetMultipartFields(fields...)

func (*Request) SetMultipartFormData ¶

func (r *Request) SetMultipartFormData(data map[string]string) *Request

SetMultipartFormData method allows simple form data to be attached to the request as `multipart:form-data`

func (*Request) SetMultipartOrderedFormData ¶

func (r *Request) SetMultipartOrderedFormData(name string, values []string) *Request

SetMultipartOrderedFormData method allows add ordered form data to be attached to the request as `multipart:form-data`

func (*Request) SetOutputFile ¶

func (r *Request) SetOutputFile(file string) *Request

SetOutputFile method sets the output file for the current HTTP request. The current HTTP response will be saved in the given file. It is similar to the `curl -o` flag.

Absolute path or relative path can be used.

If it is a relative path, then the output file goes under the output directory, as mentioned in the Client.SetOutputDirectory.

client.R().
	SetOutputFile("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip").
	Get("http://bit.ly/1LouEKr")

NOTE: In this scenario

  • [Response.BodyBytes] might be nil.
  • Response.Body might be already read.

func (*Request) SetPathParam ¶

func (r *Request) SetPathParam(param, value string) *Request

SetPathParam method sets a single URL path key-value pair in the Resty current request instance.

client.R().SetPathParam("userId", "sample@sample.com")

Result:
   URL - /v1/users/{userId}/details
   Composed URL - /v1/users/sample@sample.com/details

client.R().SetPathParam("path", "groups/developers")

Result:
   URL - /v1/users/{userId}/details
   Composed URL - /v1/users/groups%2Fdevelopers/details

It replaces the value of the key while composing the request URL. The values will be escaped using function url.PathEscape.

It overrides the path parameter set at the client instance level.

func (*Request) SetPathParams ¶

func (r *Request) SetPathParams(params map[string]string) *Request

SetPathParams method sets multiple URL path key-value pairs at one go in the Resty current request instance.

client.R().SetPathParams(map[string]string{
	"userId":       "sample@sample.com",
	"subAccountId": "100002",
	"path":         "groups/developers",
})

Result:
   URL - /v1/users/{userId}/{subAccountId}/{path}/details
   Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details

It replaces the value of the key while composing the request URL. The values will be escaped using function url.PathEscape.

It overrides the path parameter set at the client instance level.

func (*Request) SetQueryParam ¶

func (r *Request) SetQueryParam(param, value string) *Request

SetQueryParam method sets a single parameter and its value in the current request. It will be formed as a query string for the request.

For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark.

client.R().
	SetQueryParam("search", "kitchen papers").
	SetQueryParam("size", "large")

It overrides the query parameter value set at the client instance level.

func (*Request) SetQueryParams ¶

func (r *Request) SetQueryParams(params map[string]string) *Request

SetQueryParams method sets multiple parameters and their values at one go in the current request. It will be formed as a query string for the request.

For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark.

client.R().
	SetQueryParams(map[string]string{
		"search": "kitchen papers",
		"size": "large",
	})

It overrides the query parameter value set at the client instance level.

func (*Request) SetQueryParamsFromValues ¶

func (r *Request) SetQueryParamsFromValues(params url.Values) *Request

SetQueryParamsFromValues method appends multiple parameters with multi-value (url.Values) at one go in the current request. It will be formed as query string for the request.

For Example: `status=pending&status=approved&status=open` in the URL after the `?` mark.

client.R().
	SetQueryParamsFromValues(url.Values{
		"status": []string{"pending", "approved", "open"},
	})

It overrides the query parameter value set at the client instance level.

func (*Request) SetQueryString ¶

func (r *Request) SetQueryString(query string) *Request

SetQueryString method provides the ability to use string as an input to set URL query string for the request.

client.R().
	SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")

It overrides the query parameter value set at the client instance level.

func (*Request) SetRawPathParam ¶

func (r *Request) SetRawPathParam(param, value string) *Request

SetRawPathParam method sets a single URL path key-value pair in the Resty current request instance.

client.R().SetPathParam("userId", "sample@sample.com")

Result:
   URL - /v1/users/{userId}/details
   Composed URL - /v1/users/sample@sample.com/details

client.R().SetPathParam("path", "groups/developers")

Result:
   URL - /v1/users/{userId}/details
   Composed URL - /v1/users/groups/developers/details

It replaces the value of the key while composing the request URL. The value will be used as-is and has not been escaped.

It overrides the raw path parameter set at the client instance level.

func (*Request) SetRawPathParams ¶

func (r *Request) SetRawPathParams(params map[string]string) *Request

SetRawPathParams method sets multiple URL path key-value pairs at one go in the Resty current request instance.

client.R().SetPathParams(map[string]string{
	"userId": "sample@sample.com",
	"subAccountId": "100002",
	"path":         "groups/developers",
})

Result:
   URL - /v1/users/{userId}/{subAccountId}/{path}/details
   Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details

It replaces the value of the key while composing the request URL. The value will be used as-is and has not been escaped.

It overrides the raw path parameter set at the client instance level.

func (*Request) SetResponseBodyLimit ¶

func (r *Request) SetResponseBodyLimit(v int64) *Request

SetResponseBodyLimit method sets a maximum body size limit in bytes on response, avoid reading too much data to memory.

Client will return resty.ErrResponseBodyTooLarge if the body size of the body in the uncompressed response is larger than the limit. Body size limit will not be enforced in the following cases:

  • ResponseBodyLimit <= 0, which is the default behavior.
  • Request.SetOutputFile is called to save response data to the file.
  • "DoNotParseResponse" is set for client or request.

It overrides the value set at the client instance level, see Client.SetResponseBodyLimit

func (*Request) SetResponseBodyUnlimitedReads ¶

func (r *Request) SetResponseBodyUnlimitedReads(b bool) *Request

SetResponseBodyUnlimitedReads method is to turn on/off the response body copy that provides an ability to do unlimited reads.

It overrides the value set at the client level; see Client.SetResponseBodyUnlimitedReads

Unlimited reads are possible in a few scenarios, even without enabling it.

  • When debug mode is enabled

NOTE: Use with care

  • Turning on this feature uses additional memory to store a copy of the response body buffer.

func (*Request) SetResult ¶

func (r *Request) SetResult(v any) *Request

SetResult method is to register the response `Result` object for automatic unmarshalling of the HTTP response if the response status code is between 200 and 299, and the content type is JSON or XML.

Note: Request.SetResult input can be a pointer or non-pointer.

The pointer with handle

authToken := &AuthToken{}
client.R().SetResult(authToken)

// Can be accessed via -
fmt.Println(authToken) OR fmt.Println(response.Result().(*AuthToken))

OR -

The pointer without handle or non-pointer

client.R().SetResult(&AuthToken{})
// OR
client.R().SetResult(AuthToken{})

// Can be accessed via -
fmt.Println(response.Result().(*AuthToken))

func (*Request) SetRetryCount ¶

func (r *Request) SetRetryCount(count int) *Request

SetRetryCount method enables retry on Resty client and allows you to set no. of retry count.

first attempt + retry count = total attempts

See Request.SetRetryStrategy

NOTE:

func (*Request) SetRetryDefaultConditions ¶

func (r *Request) SetRetryDefaultConditions(b bool) *Request

SetRetryDefaultConditions method is used to enable/disable the Resty's default retry conditions on request level

It overrides value set at the client instance level, see Client.SetRetryDefaultConditions

func (*Request) SetRetryMaxWaitTime ¶

func (r *Request) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Request

SetRetryMaxWaitTime method sets the max wait time for sleep before retrying

Default is 2 seconds.

func (*Request) SetRetryStrategy ¶

func (r *Request) SetRetryStrategy(rs RetryStrategyFunc) *Request

SetRetryStrategy method used to set the custom Retry strategy on request, it is used to get wait time before each retry. It overrides the retry strategy set at the client instance level, see Client.SetRetryStrategy

Default (nil) implies capped exponential backoff with a jitter strategy

func (*Request) SetRetryWaitTime ¶

func (r *Request) SetRetryWaitTime(waitTime time.Duration) *Request

SetRetryWaitTime method sets the default wait time for sleep before retrying

Default is 100 milliseconds.

func (*Request) SetTimeout ¶

func (r *Request) SetTimeout(timeout time.Duration) *Request

SetTimeout method is used to set a timeout for the current request

client.R().SetTimeout(1 * time.Minute)

It overrides the timeout set at the client instance level, See Client.SetTimeout

NOTE: Resty uses context.WithTimeout on the request, it does not use http.Client.Timeout

func (*Request) SetTrace ¶

func (r *Request) SetTrace(t bool) *Request

SetTrace method is used to turn on/off the trace capability at the request level

See Request.EnableTrace or Client.SetTrace

func (*Request) SetURL ¶

func (r *Request) SetURL(url string) *Request

SetURL method used to set the request URL for the request

func (*Request) SetUnescapeQueryParams ¶

func (r *Request) SetUnescapeQueryParams(unescape bool) *Request

SetUnescapeQueryParams method sets the choice of unescape query parameters for the request URL. To prevent broken URL, Resty replaces space (" ") with "+" in the query parameters.

This method overrides the value set by Client.SetUnescapeQueryParams

NOTE: Request failure is possible due to non-standard usage of Unescaped Query Parameters.

func (*Request) Trace ¶

func (r *Request) Trace(url string) (*Response, error)

Trace method does TRACE HTTP request. It's defined in section 4.3.8 of RFC7231.

func (*Request) TraceInfo ¶

func (r *Request) TraceInfo() TraceInfo

TraceInfo method returns the trace info for the request. If either the Client.EnableTrace or Request.EnableTrace function has not been called before the request is made, an empty resty.TraceInfo object is returned.

func (*Request) WithContext ¶

func (r *Request) WithContext(ctx context.Context) *Request

WithContext method returns a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil. It does not affect the Request.RawRequest that was already created.

If you want this method to take effect, use this method before invoking Request.Send or Request.HTTPVerb methods.

See Request.SetContext, Request.Clone

type RequestFeedback ¶

type RequestFeedback struct {
	BaseURL string
	Success bool
	Attempt int
}

RequestFeedback struct is used to send the request feedback to load balancing algorithm

type RequestFunc ¶

type RequestFunc func(*Request) *Request

RequestFunc type is for extended manipulation of the Request instance

type RequestMiddleware ¶

type RequestMiddleware func(*Client, *Request) error

RequestMiddleware type is for request middleware, called before a request is sent

type Response ¶

type Response struct {
	Request     *Request
	Body        io.ReadCloser
	RawResponse *http.Response
	IsRead      bool

	// Err field used to cascade the response middleware error
	// in the chain
	Err error
	// contains filtered or unexported fields
}

Response struct holds response values of executed requests.

func (*Response) Bytes ¶

func (r *Response) Bytes() []byte

Bytes method returns the body of the HTTP response as a byte slice. It returns an empty byte slice if it is nil or the body is zero length.

NOTE:

func (*Response) Cookies ¶

func (r *Response) Cookies() []*http.Cookie

Cookies method to returns all the response cookies

func (*Response) Error ¶

func (r *Response) Error() any

Error method returns the error object if it has one

See Request.SetError, Client.SetError

func (*Response) Header ¶

func (r *Response) Header() http.Header

Header method returns the response headers

func (*Response) IsError ¶

func (r *Response) IsError() bool

IsError method returns true if HTTP status `code >= 400` otherwise false.

func (*Response) IsSuccess ¶

func (r *Response) IsSuccess() bool

IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.

func (*Response) Proto ¶

func (r *Response) Proto() string

Proto method returns the HTTP response protocol used for the request.

func (*Response) ReceivedAt ¶

func (r *Response) ReceivedAt() time.Time

ReceivedAt method returns the time we received a response from the server for the request.

func (*Response) Result ¶

func (r *Response) Result() any

Result method returns the response value as an object if it has one

See Request.SetResult

func (*Response) Size ¶

func (r *Response) Size() int64

Size method returns the HTTP response size in bytes. Yeah, you can rely on HTTP `Content-Length` header, however it won't be available for chucked transfer/compressed response. Since Resty captures response size details when processing the response body when possible. So that users get the actual size of response bytes.

func (*Response) Status ¶

func (r *Response) Status() string

Status method returns the HTTP status string for the executed request.

Example: 200 OK

func (*Response) StatusCode ¶

func (r *Response) StatusCode() int

StatusCode method returns the HTTP status code for the executed request.

Example: 200

func (*Response) String ¶

func (r *Response) String() string

String method returns the body of the HTTP response as a `string`. It returns an empty string if it is nil or the body is zero length.

NOTE:

func (*Response) Time ¶

func (r *Response) Time() time.Duration

Time method returns the duration of HTTP response time from the request we sent and received a request.

See Response.ReceivedAt to know when the client received a response and see `Response.Request.Time` to know when the client sent a request.

type ResponseError ¶

type ResponseError struct {
	Response *Response
	Err      error
}

ResponseError is a wrapper that includes the server response with an error. Neither the err nor the response should be nil.

func (*ResponseError) Error ¶

func (e *ResponseError) Error() string

func (*ResponseError) Unwrap ¶

func (e *ResponseError) Unwrap() error

type ResponseMiddleware ¶

type ResponseMiddleware func(*Client, *Response) error

ResponseMiddleware type is for response middleware, called after a response has been received

type RetryConditionFunc ¶

type RetryConditionFunc func(*Response, error) bool

RetryConditionFunc type is for the retry condition function input: non-nil Response OR request execution error

type RetryHookFunc ¶

type RetryHookFunc func(*Response, error)

RetryHookFunc is for side-effecting functions triggered on retry

type RetryStrategyFunc ¶

type RetryStrategyFunc func(*Response, error) (time.Duration, error)

RetryStrategyFunc type is for custom retry strategy implementation By default Resty uses the capped exponential backoff with a jitter strategy

type RoundRobin ¶

type RoundRobin struct {
	// contains filtered or unexported fields
}

RoundRobin struct used to implement the Round-Robin(RR) request load balancer algorithm

func NewRoundRobin ¶

func NewRoundRobin(baseURLs ...string) (*RoundRobin, error)

NewRoundRobin method creates the new Round-Robin(RR) request load balancer instance with given base URLs

func (*RoundRobin) Close ¶

func (rr *RoundRobin) Close() error

Close method does nothing in Round-Robin(RR) request load balancer

func (*RoundRobin) Feedback ¶

func (rr *RoundRobin) Feedback(_ *RequestFeedback)

Feedback method does nothing in Round-Robin(RR) request load balancer

func (*RoundRobin) Next ¶

func (rr *RoundRobin) Next() (string, error)

Next method returns the next Base URL based on the Round-Robin(RR) algorithm

func (*RoundRobin) Refresh ¶

func (rr *RoundRobin) Refresh(baseURLs ...string) error

Refresh method reset the existing Base URLs with the given Base URLs slice to refresh it

type SRVWeightedRoundRobin ¶

type SRVWeightedRoundRobin struct {
	Service    string
	Proto      string
	DomainName string
	HttpScheme string
	// contains filtered or unexported fields
}

SRVWeightedRoundRobin struct used to implement SRV Weighted Round-Robin(RR) algorithm

func NewSRVWeightedRoundRobin ¶

func NewSRVWeightedRoundRobin(service, proto, domainName, httpScheme string) (*SRVWeightedRoundRobin, error)

NewSRVWeightedRoundRobin method creates a new Weighted Round-Robin(WRR) load balancer instance with given SRV values

func (*SRVWeightedRoundRobin) Close ¶

func (swrr *SRVWeightedRoundRobin) Close() error

Close method does the cleanup by stopping the time.Ticker SRV Base URL based on Weighted Round-Robin(WRR) request load balancer

func (*SRVWeightedRoundRobin) Feedback ¶

func (swrr *SRVWeightedRoundRobin) Feedback(f *RequestFeedback)

Feedback method does nothing in SRV Base URL based on Weighted Round-Robin(WRR) request load balancer

func (*SRVWeightedRoundRobin) Next ¶

func (swrr *SRVWeightedRoundRobin) Next() (string, error)

Next method returns the next SRV Base URL based on Weighted Round-Robin(RR)

func (*SRVWeightedRoundRobin) Refresh ¶

func (swrr *SRVWeightedRoundRobin) Refresh() error

Refresh method reset the values based net.LookupSRV values to refresh it

func (*SRVWeightedRoundRobin) SetOnStateChange ¶

func (swrr *SRVWeightedRoundRobin) SetOnStateChange(fn HostStateChangeFunc)

SetOnStateChange method used to set a callback for the host transition state

func (*SRVWeightedRoundRobin) SetRecoveryDuration ¶

func (swrr *SRVWeightedRoundRobin) SetRecoveryDuration(d time.Duration)

SetRecoveryDuration method is used to change the existing recovery duration for the host

func (*SRVWeightedRoundRobin) SetRefreshDuration ¶

func (swrr *SRVWeightedRoundRobin) SetRefreshDuration(d time.Duration)

SetRefreshDuration method assists in changing the default (180 seconds) refresh duration

type State ¶

type State int
const (
	StateInActive State = iota
	StateActive
)

Host transition states

type SuccessHook ¶

type SuccessHook func(*Client, *Response)

SuccessHook type is for reacting to request success

type TLSClientConfiger ¶

type TLSClientConfiger interface {
	TLSClientConfig() *tls.Config
	SetTLSClientConfig(*tls.Config) error
}

TLSClientConfiger interface is to configure TLS Client configuration on custom transport implemented using http.RoundTripper

type TraceInfo ¶

type TraceInfo struct {
	// DNSLookup is the duration that transport took to perform
	// DNS lookup.
	DNSLookup time.Duration

	// ConnTime is the duration it took to obtain a successful connection.
	ConnTime time.Duration

	// TCPConnTime is the duration it took to obtain the TCP connection.
	TCPConnTime time.Duration

	// TLSHandshake is the duration of the TLS handshake.
	TLSHandshake time.Duration

	// ServerTime is the server's duration for responding to the first byte.
	ServerTime time.Duration

	// ResponseTime is the duration since the first response byte from the server to
	// request completion.
	ResponseTime time.Duration

	// TotalTime is the duration of the total time request taken end-to-end.
	TotalTime time.Duration

	// IsConnReused is whether this connection has been previously
	// used for another HTTP request.
	IsConnReused bool

	// IsConnWasIdle is whether this connection was obtained from an
	// idle pool.
	IsConnWasIdle bool

	// ConnIdleTime is the duration how long the connection that was previously
	// idle, if IsConnWasIdle is true.
	ConnIdleTime time.Duration

	// RequestAttempt is to represent the request attempt made during a Resty
	// request execution flow, including retry count.
	RequestAttempt int

	// RemoteAddr returns the remote network address.
	RemoteAddr net.Addr
}

TraceInfo struct is used to provide request trace info such as DNS lookup duration, Connection obtain duration, Server processing duration, etc.

func (TraceInfo) String ¶

func (ti TraceInfo) String() string

String method returns string representation of request trace information.

type TransportSettings ¶

type TransportSettings struct {
	// DialerTimeout, default value is `30` seconds.
	DialerTimeout time.Duration

	// DialerKeepAlive, default value is `30` seconds.
	DialerKeepAlive time.Duration

	// IdleConnTimeout, default value is `90` seconds.
	IdleConnTimeout time.Duration

	// TLSHandshakeTimeout, default value is `10` seconds.
	TLSHandshakeTimeout time.Duration

	// ExpectContinueTimeout, default value is `1` seconds.
	ExpectContinueTimeout time.Duration

	// ResponseHeaderTimeout, added to provide ability to
	// set value. No default value in Resty, the Go
	// HTTP client default value applies.
	ResponseHeaderTimeout time.Duration

	// MaxIdleConns, default value is `100`.
	MaxIdleConns int

	// MaxIdleConnsPerHost, default value is `runtime.GOMAXPROCS(0) + 1`.
	MaxIdleConnsPerHost int

	// DisableKeepAlives, default value is `false`.
	DisableKeepAlives bool

	// MaxResponseHeaderBytes, added to provide ability to
	// set value. No default value in Resty, the Go
	// HTTP client default value applies.
	MaxResponseHeaderBytes int64

	// WriteBufferSize, added to provide ability to
	// set value. No default value in Resty, the Go
	// HTTP client default value applies.
	WriteBufferSize int

	// ReadBufferSize, added to provide ability to
	// set value. No default value in Resty, the Go
	// HTTP client default value applies.
	ReadBufferSize int
}

TransportSettings struct is used to define custom dialer and transport values for the Resty client. Please refer to individual struct fields to know the default values.

Also, refer to https://pkg.go.dev/net/http#Transport for more details.

type WeightedRoundRobin ¶

type WeightedRoundRobin struct {
	// contains filtered or unexported fields
}

WeightedRoundRobin struct used to represent the host details for Weighted Round-Robin(WRR) algorithm implementation

func NewWeightedRoundRobin ¶

func NewWeightedRoundRobin(recovery time.Duration, hosts ...*Host) (*WeightedRoundRobin, error)

NewWeightedRoundRobin method creates the new Weighted Round-Robin(WRR) request load balancer instance with given recovery duration and hosts slice

func (*WeightedRoundRobin) Close ¶

func (wrr *WeightedRoundRobin) Close() error

Close method does the cleanup by stopping the time.Ticker on Weighted Round-Robin(WRR) request load balancer

func (*WeightedRoundRobin) Feedback ¶

func (wrr *WeightedRoundRobin) Feedback(f *RequestFeedback)

Feedback method process the request feedback for Weighted Round-Robin(WRR) request load balancer

func (*WeightedRoundRobin) Next ¶

func (wrr *WeightedRoundRobin) Next() (string, error)

Next method returns the next Base URL based on Weighted Round-Robin(WRR)

func (*WeightedRoundRobin) Refresh ¶

func (wrr *WeightedRoundRobin) Refresh(hosts ...*Host) error

Refresh method reset the existing values with the given Host slice to refresh it

func (*WeightedRoundRobin) SetOnStateChange ¶

func (wrr *WeightedRoundRobin) SetOnStateChange(fn HostStateChangeFunc)

SetOnStateChange method used to set a callback for the host transition state

func (*WeightedRoundRobin) SetRecoveryDuration ¶

func (wrr *WeightedRoundRobin) SetRecoveryDuration(d time.Duration)

SetRecoveryDuration method is used to change the existing recovery duration for the host

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL