zdpgo_resty

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2024 License: Apache-2.0 Imports: 37 Imported by: 1

README

zdpgo_resty

基于resty二次开发的http client客户端工具,专用于发送HTTP请求,提供低代码开发及详细的中文文档

特性

  • 支持发送 GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS 等请求
  • 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
  • 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 GenerateCurlCommand(You should turn on EnableTrace, otherwise the curl command will not contain the body)
    • Debug mode - clean and informative logging presentation
    • Gzip - Go does it automatically also resty has fallback handling too
    • Works fine with HTTP/2 and HTTP/1.1
  • Bazel support
  • Easily mock Resty for testing, for e.g.
  • Well tested client library

Installation

# Go Modules
require github.com/zhangdapeng520/zdpgo_resty v0.1.0

使用教程

发送POST请求
// Create a Resty Client
client := resty.New()

resp, err := client.R().
EnableTrace(). // You should turn on `EnableTrace`, otherwise the curl command will not contain the body
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")

// 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())
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 {
// 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 {
// 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...
})
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.

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.

Documentation

Overview

package zdpgo_resty provides Simple HTTP and REST client library for Go.

Index

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"
)
View Source
const Version = "2.14.0"

Version # of resty

Variables

View Source
var (
	ErrDigestBadChallenge    = errors.New("digest: challenge is bad")
	ErrDigestCharset         = errors.New("digest: unsupported charset")
	ErrDigestAlgNotSupported = errors.New("digest: algorithm is not supported")
	ErrDigestQopNotSupported = errors.New("digest: no supported qop in list")
	ErrDigestNoQop           = errors.New("digest: qop must be specified")
)
View Source
var (
	// Since v2.8.0
	ErrAutoRedirectDisabled = errors.New("auto redirect is disabled")
)
View Source
var ErrRateLimitExceeded = errors.New("rate limit exceeded")
View Source
var ErrResponseBodyTooLarge = errors.New("resty: response body too large")

Functions

func Backoff

func Backoff(operation func() (*Response, error), options ...Option) error

Backoff retries with increasing timeout duration up until X amount of retries (Default is 3 attempts, Override with option Retries(n))

func DetectContentType

func DetectContentType(body interface{}) string

DetectContentType method is used to figure out `Request.Body` content type for request header

func IsJSONType

func IsJSONType(ct string) bool

IsJSONType method is to check JSON content type or not

func IsStringEmpty

func IsStringEmpty(str string) bool

IsStringEmpty method tells whether given string is empty or not

func IsXMLType

func IsXMLType(ct string) bool

IsXMLType method is to check XML content type or not

func Unmarshalc

func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error)

Unmarshalc content into object from JSON or XML

Types

type Client

type Client struct {
	BaseURL               string
	HostURL               string // Deprecated: use BaseURL instead. To be removed in v3.0.0 release.
	QueryParam            url.Values
	FormData              url.Values
	PathParams            map[string]string
	RawPathParams         map[string]string
	Header                http.Header
	UserInfo              *User
	Token                 string
	AuthScheme            string
	Cookies               []*http.Cookie
	Error                 reflect.Type
	Debug                 bool
	DisableWarn           bool
	AllowGetMethodPayload bool
	RetryCount            int
	RetryWaitTime         time.Duration
	RetryMaxWaitTime      time.Duration
	RetryConditions       []RetryConditionFunc
	RetryHooks            []OnRetryFunc
	RetryAfter            RetryAfterFunc
	RetryResetReaders     bool
	JSONMarshal           func(v interface{}) ([]byte, error)
	JSONUnmarshal         func(data []byte, v interface{}) error
	XMLMarshal            func(v interface{}) ([]byte, error)
	XMLUnmarshal          func(data []byte, v interface{}) error

	// HeaderAuthorizationKey is used to set/access Request Authorization header
	// value when `SetAuthToken` option is used.
	HeaderAuthorizationKey string
	ResponseBodyLimit      int
	// contains filtered or unexported fields
}

Client struct is used to create Resty client with client level settings, these settings are applicable to all the request raised from the client.

Resty also provides an options to override most of the client settings at request level.

func New

func New() *Client

New method creates a new Resty client.

func NewWithClient

func NewWithClient(hc *http.Client) *Client

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

func NewWithLocalAddr

func NewWithLocalAddr(localAddr net.Addr) *Client

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

func (*Client) AddRetryAfterErrorCondition

func (c *Client) AddRetryAfterErrorCondition() *Client

AddRetryAfterErrorCondition adds the basic condition of retrying after encountering an error from the http response

Since v2.6.0

func (*Client) AddRetryCondition

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

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

Note: These retry conditions are applied on all Request made using this Client. For Request specific retry conditions check *Request.AddRetryCondition

func (*Client) AddRetryHook

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

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

Since v2.6.0

func (*Client) Clone

func (c *Client) Clone() *Client

Clone returns a clone of the original client.

Be careful when using this function: - Interface values are not deeply cloned. Thus, both the original and the clone will use the same value. - This function is not safe for concurrent use. You should only use this when you are sure that the client is not being used by any other goroutine.

Since v2.12.0

func (*Client) DisableTrace

func (c *Client) DisableTrace() *Client

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

Since v2.0.0

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

Also `Request.EnableTrace` available too to get trace info for single request.

Since v2.0.0

func (*Client) GetClient

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

GetClient method returns the current `http.Client` used by the resty client.

func (*Client) IsProxySet

func (c *Client) IsProxySet() bool

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

func (*Client) NewRequest

func (c *Client) NewRequest() *Request

NewRequest is an alias for method `R()`. Creates a new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc.

func (*Client) OnAfterResponse

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

OnAfterResponse method appends response middleware into the after response chain. Once we receive response from host server, default Resty response middleware gets applied and then user assigned response middlewares applied.

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

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

func (*Client) OnBeforeRequest

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

OnBeforeRequest method appends a request middleware into the before request chain. The user defined middlewares get applied before the default Resty request middlewares. After all middlewares have been applied, the request is sent from Resty to the host server.

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

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

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 OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute() that completes.

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 OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute() that completes.

Since v2.8.0

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 OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute() that completes. If an OnSuccess, OnError, or OnInvalid callback panics, then the exactly one rule can be violated.

Since v2.8.0

func (*Client) OnRequestLog

func (c *Client) OnRequestLog(rl RequestLogCallback) *Client

OnRequestLog method used to set request log callback into Resty. Registered callback gets called before the resty actually logs the information.

func (*Client) OnResponseLog

func (c *Client) OnResponseLog(rl ResponseLogCallback) *Client

OnResponseLog method used to set response log callback into Resty. Registered callback gets called before the resty actually 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 OnSuccess, OnError, OnInvalid, OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute() that completes.

Since v2.8.0

func (*Client) R

func (c *Client) R() *Request

R method creates a new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc.

func (*Client) RemoveProxy

func (c *Client) RemoveProxy() *Client

RemoveProxy method removes the proxy configuration from Resty client

client.RemoveProxy()

func (*Client) SetAllowGetMethodPayload

func (c *Client) SetAllowGetMethodPayload(a bool) *Client

SetAllowGetMethodPayload method allows the GET method with payload on Resty client.

For Example: Resty allows the user sends request with a payload on HTTP GET method.

client.SetAllowGetMethodPayload(true)

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 or set one at the request level is supported.

Information about auth schemes can be found in RFC7235 which is linked to below along with the page containing the currently defined official authentication schemes:

https://tools.ietf.org/html/rfc7235
https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes

See `Request.SetAuthToken`.

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 `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 or set one at the request level is supported.

See `Request.SetAuthToken`.

func (*Client) SetBaseURL

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

SetBaseURL method is to set Base URL in the client instance. It will be used with request raised from this client with relative URL

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

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

Since v2.7.0

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 gets added to all the request raised from this client instance. Also it can be overridden or set one at the request level is supported.

See `Request.SetBasicAuth`.

func (*Client) SetCertificates

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

SetCertificates method helps to set client certificates into Resty conveniently.

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

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 an option to enable for particular request. See `Request.SetContentLength`

func (*Client) SetCookie

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

SetCookie method appends a single cookie in the client instance. These cookies will be added to all the request raised 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. Its way to override default.

For Example: sometimes we don't want to save cookies in api contacting, 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 request raised 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 Resty client. Client logs details of every request and response. For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. For `Response` it logs information such as Status, Response Time, Headers, Body if it has one.

client.SetDebug(true)

Also it can be enabled at request level for particular request, see `Request.SetDebug`.

func (*Client) SetDebugBodyLimit

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

SetDebugBodyLimit sets the maximum size 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 Access auth scheme for the client. If a server responds with 401 and sends a Digest challenge in the WWW-Authenticate Header, requests will be resent with the appropriate 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 RFC7616:

https://datatracker.ietf.org/doc/html/rfc7616

See `Request.SetDigestAuth`.

func (*Client) SetDisableWarn

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

SetDisableWarn method disables the warning message on Resty client.

For Example: Resty warns the user when BasicAuth used on non-TLS mode.

client.SetDisableWarn(true)

func (*Client) SetDoNotParseResponse

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

SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, otherwise you might get into connection leaks, no connection reuse.

Note: Response middlewares are not applicable, if you use this option. Basically you have taken over the control of response parsing from `Resty`.

func (*Client) SetError

func (c *Client) SetError(err interface{}) *Client

SetError method is to register the global or client common `Error` object into Resty. It is used for automatic unmarshalling if response status code is greater than 399 and content type either JSON or XML. Can be pointer or 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's applicable only HTTP method `POST` and `PUT` and request content type would be set as `application/x-www-form-urlencoded`. These form data will be added to all the request raised from this client instance. Also it can be overridden at request level form data.

See `Request.SetFormData`.

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

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 raised from this client instance. Also it can be overridden at 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 to set a single header field and its value verbatim in the current request.

For Example: To set `all_lowercase` and `UPPERCASE` as `available`.

client.R().
	SetHeaderVerbatim("all_lowercase", "available").
	SetHeaderVerbatim("UPPERCASE", "available")

Also you can override header value, which was set at client instance level.

Since v2.6.0

func (*Client) SetHeaders

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

SetHeaders method sets multiple headers field and its values at one go in the client instance. These headers will be applied to all requests raised 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) SetHostURL deprecated

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

SetHostURL method is to set Host URL in the client instance. It will be used with request raised from this client with relative URL

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

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

Deprecated: use SetBaseURL instead. To be removed in v3.0.0 release.

func (*Client) SetJSONEscapeHTML

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

SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal.

Note: This option only applicable to standard JSON Marshaller.

func (*Client) SetJSONMarshaler

func (c *Client) SetJSONMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client

SetJSONMarshaler method sets the JSON marshaler function to marshal the request body. By default, Resty uses `encoding/json` package to marshal the request body.

Since v2.8.0

func (*Client) SetJSONUnmarshaler

func (c *Client) SetJSONUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client

SetJSONUnmarshaler method sets the JSON unmarshaler function to unmarshal the response body. By default, Resty uses `encoding/json` package to unmarshal the response body.

Since v2.8.0

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 output directory for saving HTTP response into file. If the output directory not exists then resty creates one. This setting is optional one, if you're planning using absolute path in `Request.SetOutput` and can used together.

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

func (*Client) SetPathParam

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

SetPathParam method sets 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.

Also it can be overridden at request level Path Params options, 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.

Also it can be overridden at request level Path Params options, see `Request.SetPathParam` or `Request.SetPathParams`.

func (*Client) SetPreRequestHook

func (c *Client) SetPreRequestHook(h PreRequestHook) *Client

SetPreRequestHook method sets the given pre-request function into resty client. It is called right before the request is fired.

Note: Only one pre-request hook can be registered. Use `client.OnBeforeRequest` for multiple.

func (*Client) SetProxy

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

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

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

OR Without this `SetProxy` method, you could also set Proxy via environment variable.

Refer to godoc `http.ProxyFromEnvironment`.

func (*Client) SetQueryParam

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

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

For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. These query params will be added to all the request raised from this client instance. Also it can be overridden at request level Query Param options.

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 query string for the request.

For Example: `search=kitchen%20papers&size=large` in the URL after `?` mark. These query params will be added to all the request raised from this client instance. Also it can be overridden at request level Query Param options.

See `Request.SetQueryParams` or `Request.SetQueryParam`.

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

func (*Client) SetRateLimiter

func (c *Client) SetRateLimiter(rl RateLimiter) *Client

SetRateLimiter sets an optional `RateLimiter`. If set the rate limiter will control all requests made with this client.

Since v2.9.0

func (*Client) SetRawPathParam

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

SetRawPathParam method sets 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.

Also it can be overridden at request level Path Params options, see `Request.SetPathParam` or `Request.SetPathParams`.

Since v2.8.0

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.

Also it can be overridden at request level Path Params options, see `Request.SetPathParam` or `Request.SetPathParams`.

Since v2.8.0

func (*Client) SetRedirectPolicy

func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client

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

client.SetRedirectPolicy(FlexibleRedirectPolicy(20))

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

func (*Client) SetResponseBodyLimit

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

SetResponseBodyLimit set a max body size limit on response, avoid reading too many data to memory.

Client will return [resty.ErrResponseBodyTooLarge] if uncompressed response body size if larger than limit. Body size limit will not be enforced in following case:

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

this can be overridden at client level with Request.SetResponseBodyLimit

func (*Client) SetRetryAfter

func (c *Client) SetRetryAfter(callback RetryAfterFunc) *Client

SetRetryAfter sets callback to calculate wait time between retries. Default (nil) implies exponential backoff with jitter

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. Resty uses a Backoff mechanism.

func (*Client) SetRetryMaxWaitTime

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

SetRetryMaxWaitTime method sets max wait time to sleep before retrying request.

Default is 2 seconds.

func (*Client) SetRetryResetReaders

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

SetRetryResetReaders method enables the Resty client to seek the start of all file readers given as multipart files, if the given object implements `io.ReadSeeker`.

Since ...

func (*Client) SetRetryWaitTime

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

SetRetryWaitTime method sets default wait time to sleep before retrying request.

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 Resty client

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

func (*Client) SetRootCertificateFromString

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

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

client.SetRootCertificateFromString("pem file content")

func (*Client) SetScheme

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

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

client.SetScheme("http")

func (*Client) SetTLSClientConfig

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

SetTLSClientConfig method sets TLSClientConfig for underling client Transport.

For Example:

// 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 })

Note: This method overwrites existing `TLSClientConfig`.

func (*Client) SetTimeout

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

SetTimeout method sets timeout for request raised from client.

client.SetTimeout(time.Duration(1 * time.Minute))

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.

Note:

- If transport is not type of `*http.Transport` then you may not be able to take advantage of some of the Resty client settings.

- It overwrites the Resty client transport instance and it's configurations.

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)

func (*Client) SetXMLMarshaler

func (c *Client) SetXMLMarshaler(marshaler func(v interface{}) ([]byte, error)) *Client

SetXMLMarshaler method sets the XML marshaler function to marshal the request body. By default, Resty uses `encoding/xml` package to marshal the request body.

Since v2.8.0

func (*Client) SetXMLUnmarshaler

func (c *Client) SetXMLUnmarshaler(unmarshaler func(data []byte, v interface{}) error) *Client

SetXMLUnmarshaler method sets the XML unmarshaler function to unmarshal the response body. By default, Resty uses `encoding/xml` package to unmarshal the response body.

Since v2.8.0

func (*Client) Transport

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

Transport method returns `*http.Transport` currently in use or error in case currently used `transport` is not a `*http.Transport`.

Since v2.8.0 become exported method.

type ErrorHook

type ErrorHook func(*Request, error)

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

type File

type File struct {
	Name      string
	ParamName string
	io.Reader
}

File struct represent file information for multipart request

func (*File) String

func (f *File) String() string

String returns string value of current file details

type Logger

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

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

type MultipartField

type MultipartField struct {
	Param       string
	FileName    string
	ContentType string
	io.Reader
}

MultipartField struct represent custom data part for multipart request

type OnRetryFunc

type OnRetryFunc func(*Response, error)

OnRetryFunc is for side-effecting functions triggered on retry

type Option

type Option func(*Options)

Option is to create convenient retry options like wait time, max retries, etc.

func MaxWaitTime

func MaxWaitTime(value time.Duration) Option

MaxWaitTime sets the max wait time to sleep between requests

func ResetMultipartReaders

func ResetMultipartReaders(value bool) Option

ResetMultipartReaders sets a boolean value which will lead the start being seeked out on all multipart file readers, if they implement io.ReadSeeker

func Retries

func Retries(value int) Option

Retries sets the max number of retries

func RetryConditions

func RetryConditions(conditions []RetryConditionFunc) Option

RetryConditions sets the conditions that will be checked for retry.

func RetryHooks

func RetryHooks(hooks []OnRetryFunc) Option

RetryHooks sets the hooks that will be executed after each retry

func WaitTime

func WaitTime(value time.Duration) Option

WaitTime sets the default wait time to sleep between requests

type Options

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

Options struct is used to hold retry settings.

type PreRequestHook

type PreRequestHook func(*Client, *http.Request) error

PreRequestHook type is for the request hook, called right before the request is sent

type RateLimiter

type RateLimiter interface {
	Allow() bool
}

type RedirectPolicy

type RedirectPolicy interface {
	Apply(req *http.Request, via []*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 is convenient method to define domain name redirect rule in resty client. Redirect is allowed for only mentioned host in the policy.

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

func FlexibleRedirectPolicy

func FlexibleRedirectPolicy(noOfRedirect int) RedirectPolicy

FlexibleRedirectPolicy is convenient method to create No of redirect policy for HTTP client.

resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))

func NoRedirectPolicy

func NoRedirectPolicy() RedirectPolicy

NoRedirectPolicy is used to disable redirects in the HTTP client

resty.SetRedirectPolicy(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
	Token         string
	AuthScheme    string
	QueryParam    url.Values
	FormData      url.Values
	PathParams    map[string]string
	RawPathParams map[string]string
	Header        http.Header
	Time          time.Time
	Body          interface{}
	Result        interface{}

	Error      interface{}
	RawRequest *http.Request
	SRV        *SRVRecord
	UserInfo   *User
	Cookies    []*http.Cookie
	Debug      bool

	// Attempt is to represent the request attempt made during a Resty
	// request execution flow, including retry count.
	//
	// Since v2.4.0
	Attempt int
	// contains filtered or unexported fields
}

Request struct is used to compose and fire individual request from resty client. Request provides an options to override client level settings and also an options 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 that are checked to determine if the request is retried. The request will retry if any of the functions return true and error is nil.

Note: These retry conditions are checked before all retry conditions of the client.

Since v2.7.0

func (*Request) Context

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

Context method returns the Context if its already set in request otherwise it creates new one using `context.Background()`.

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) 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` available too to get trace info for all requests.

Since v2.0.0

func (*Request) Execute

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

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

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

func (*Request) ExpectContentType

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

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

func (*Request) ForceContentType

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

ForceContentType 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.ForceContentType` is set and the response `Content-Type` is available, `ForceContentType` will win.

func (*Request) GenerateCurlCommand

func (r *Request) GenerateCurlCommand() string

Generate 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`.

req := client.R()
req.Method = resty.MethodGet
req.URL = "http://httpbin.org/get"
resp, err := req.Send()

func (*Request) SetAuthScheme

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

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

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

For Example: To set the scheme to use OAuth

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

This auth header scheme gets added to all the request raised from this client instance. Also it can be overridden or set one at the request level is supported.

Information about Auth schemes can be found in RFC7235 which is linked to below along with the page containing the currently defined official authentication schemes:

https://tools.ietf.org/html/rfc7235
https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml#authschemes

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

func (*Request) SetAuthToken

func (r *Request) SetAuthToken(token 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")

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

This method overrides the credentials set by method `Client.SetBasicAuth`.

func (*Request) SetBody

func (r *Request) SetBody(body interface{}) *Request

SetBody method sets the request body for the request. It supports various realtime needs as easy. We can say its quite handy or powerful. Supported request body data types is `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 as bufferless mode while sending request.

For Example: Struct as a body input, based on content type, it will be marshalled.

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

Map as a body input, based on content type, it will be marshalled.

client.R().
	SetBody(map[string]interface{}{
		"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 request such as file upload, serialize & deserialize, etc.

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

func (*Request) SetContentLength

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

SetContentLength method sets the HTTP header `Content-Length` value for current request. By default Resty won't set `Content-Length`. Also you have an option to enable for every request.

See `Client.SetContentLength`

client.R().SetContentLength(true)

func (*Request) SetContext

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

SetContext method sets the context.Context for current Request. It allows to interrupt the request execution if ctx.Done() channel is closed. See https://blog.golang.org/context article and the "context" package documentation.

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 if already existing.

Since v2.1.0

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 if already existing.

Since v2.1.0

func (*Request) SetDebug

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

SetDebug method enables the debug mode on current request Resty request, It logs the details current request and response. For `Request` it logs information such as HTTP verb, Relative URL path, Host, Headers, Body if it has one. For `Response` it logs information such as Status, Response Time, Headers, Body if it has one.

client.R().SetDebug(true)

func (*Request) SetDigestAuth

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

SetDigestAuth method sets the Digest Access auth scheme for the HTTP request. If a server responds with 401 and sends a Digest challenge in the WWW-Authenticate Header, the request will be resent with the appropriate Authorization Header.

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

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

Information about Digest Access Authentication can be found in RFC7616:

https://datatracker.ietf.org/doc/html/rfc7616

This method overrides the username and password set by method `Client.SetDigestAuth`.

func (*Request) SetDoNotParseResponse

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

SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. Resty exposes the raw response body as `io.ReadCloser`. Also do not forget to close the body, otherwise you might get into connection leaks, no connection reuse.

Note: Response middlewares are not applicable, if you use this option. Basically you have taken over the control of response parsing from `Resty`.

func (*Request) SetError

func (r *Request) SetError(err interface{}) *Request

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

Note: Error object can be pointer or non-pointer.

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

Accessing a error value from response instance.

response.Error().(*AuthError)

func (*Request) SetFile

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

SetFile method is to set single file field name and its path for multipart upload.

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

func (*Request) SetFileReader

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

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

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 is to set multiple file field name and its path for multipart upload.

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

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

SetFormData method sets Form parameters and their values in the current request. It's applicable only HTTP method `POST` and `PUT` and 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",
	})

Also you can override form data value, which was set at client instance level.

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

Also you can override form data value, which was set at client instance level.

func (*Request) SetHeader

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

SetHeader method is to set 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")

Also you can override header value, which was set at client instance level.

func (*Request) SetHeaderMultiValues

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

SetHeaderMultiValues sets multiple headers fields and its values is list of strings at one go 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"},
	})

Also you can override header value, which was set at client instance level.

func (*Request) SetHeaderVerbatim

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

SetHeaderVerbatim method is to set a single header field and its value verbatim in the current request.

For Example: To set `all_lowercase` and `UPPERCASE` as `available`.

client.R().
	SetHeaderVerbatim("all_lowercase", "available").
	SetHeaderVerbatim("UPPERCASE", "available")

Also you can override header value, which was set at client instance level.

Since v2.6.0

func (*Request) SetHeaders

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

SetHeaders method sets multiple headers field and its 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",
	})

Also you can override header value, which was set at client instance level.

func (*Request) SetJSONEscapeHTML

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

SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal.

Note: This option only applicable to standard JSON Marshaller.

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`.

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.

Since v2.15.0

func (*Request) SetMultipartField

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

SetMultipartField method is to set custom data using io.Reader for multipart upload.

func (*Request) SetMultipartFields

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

SetMultipartFields method is to set multiple data fields using io.Reader for multipart upload.

For Example:

client.R().SetMultipartFields(
	&resty.MultipartField{
		Param:       "uploadManifest1",
		FileName:    "upload-file-1.json",
		ContentType: "application/json",
		Reader:      strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`),
	},
	&resty.MultipartField{
		Param:       "uploadManifest2",
		FileName:    "upload-file-2.json",
		ContentType: "application/json",
		Reader:      strings.NewReader(`{"input": {"name": "Uploaded document 2", "_filename" : ["file2.txt"]}}`),
	})

If you have slice already, then simply 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) SetOutput

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

SetOutput method sets the output file for current HTTP request. Current HTTP response will be saved into given file. It is similar to `curl -o` flag. Absolute path or relative path can be used. If is it relative path then output file goes under the output directory, as mentioned in the `Client.SetOutputDirectory`.

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

Note: In this scenario `Response.Body` might be nil.

func (*Request) SetPathParam

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

SetPathParam method sets 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 `url.PathEscape` function.

Also you can override Path Params value, which was set at 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 request URL. The value will be used as it is and will not be escaped.

Also you can override Path Params value, which was set at client instance level.

func (*Request) SetQueryParam

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

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

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

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

Also you can override query params value, which was set at client instance level.

func (*Request) SetQueryParams

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

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

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

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

Also you can override query params value, which was set at 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 `?` mark.

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

Also you can override query params value, which was set at client instance level.

func (*Request) SetQueryString

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

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

Using String as an input

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

func (*Request) SetRawPathParam

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

SetRawPathParam method sets 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 it is and will not be escaped.

Also you can override Path Params value, which was set at client instance level.

Since v2.8.0

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 request URL. The values will be used as they are and will not be escaped.

Also you can override Path Params value, which was set at client instance level.

Since v2.8.0

func (*Request) SetResponseBodyLimit

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

SetResponseBodyLimit set a max body size limit on response, avoid reading too many data to memory.

Request will return [resty.ErrResponseBodyTooLarge] if uncompressed response body size if larger than limit. Body size limit will not be enforced in following case:

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

This will override Client config.

func (*Request) SetResult

func (r *Request) SetResult(res interface{}) *Request

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

Note: Result object can be pointer or non-pointer.

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

Accessing a result value from response instance.

response.Result().(*AuthToken)

func (*Request) SetSRV

func (r *Request) SetSRV(srv *SRVRecord) *Request

SetSRV method sets the details to query the service SRV record and execute the request.

client.R().
	SetSRV(SRVRecord{"web", "testservice.com"}).
	Get("/get")

func (*Request) TraceInfo

func (r *Request) TraceInfo() TraceInfo

TraceInfo method returns the trace info for the request. If either the Client or Request EnableTrace function has not been called prior to the request being made, an empty TraceInfo object will be returned.

Since v2.0.0

type RequestLog

type RequestLog struct {
	Header http.Header
	Body   string
}

RequestLog struct is used to collected information from resty request instance for debug logging. It sent to request log callback before resty actually logs the information.

type RequestLogCallback

type RequestLogCallback func(*RequestLog) error

RequestLogCallback type is for request logs, called before the request is logged

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
	RawResponse *http.Response
	// contains filtered or unexported fields
}

Response struct holds response values of executed request.

func (*Response) Body

func (r *Response) Body() []byte

Body method returns HTTP response as []byte array for the executed request.

Note: `Response.Body` might be nil, if `Request.SetOutput` is used.

func (*Response) Cookies

func (r *Response) Cookies() []*http.Cookie

Cookies method to access all the response cookies

func (*Response) Error

func (r *Response) Error() interface{}

Error method returns the error object if it has one

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

func (r *Response) RawBody() io.ReadCloser

RawBody method exposes the HTTP raw response body. Use this method in-conjunction with `SetDoNotParseResponse` option otherwise you get an error as `read err: http: read on closed response body`.

Do not forget to close the body, otherwise you might get into connection leaks, no connection reuse. Basically you have taken over the control of response parsing from `Resty`.

func (*Response) ReceivedAt

func (r *Response) ReceivedAt() time.Time

ReceivedAt method returns when response got received from server for the request.

func (*Response) Result

func (r *Response) Result() interface{}

Result method returns the response value as an object if it has one

func (*Response) SetBody

func (r *Response) SetBody(b []byte) *Response

SetBody method is to set Response body in byte slice. Typically, its helpful for test cases.

resp.SetBody([]byte("This is test body content"))
resp.SetBody(nil)

Since v2.10.0

func (*Response) Size

func (r *Response) Size() int64

Size method returns the HTTP response size in bytes. Ya, you can relay on HTTP `Content-Length` header, however it won't be good for chucked transfer/compressed response. Since Resty calculates response size at the client end. You will get actual size of the http response.

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 server response as String.

func (*Response) Time

func (r *Response) Time() time.Duration

Time method returns the time of HTTP response time that from request we sent and received a request.

See `Response.ReceivedAt` to know when client received response and see `Response.Request.Time` to know when client sent a request.

type ResponseError

type ResponseError struct {
	Response *Response
	Err      error
}

ResponseError is a wrapper for including 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 ResponseLog

type ResponseLog struct {
	Header http.Header
	Body   string
}

ResponseLog struct is used to collected information from resty response instance for debug logging. It sent to response log callback before resty actually logs the information.

type ResponseLogCallback

type ResponseLogCallback func(*ResponseLog) error

ResponseLogCallback type is for response logs, called before the response is logged

type ResponseMiddleware

type ResponseMiddleware func(*Client, *Response) error

ResponseMiddleware type is for response middleware, called after a response has been received

type RetryAfterFunc

type RetryAfterFunc func(*Client, *Response) (time.Duration, error)

RetryAfterFunc returns time to wait before retry For example, it can parse HTTP Retry-After header https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html Non-nil error is returned if it is found that request is not retryable (0, nil) is a special result means 'use default algorithm'

type RetryConditionFunc

type RetryConditionFunc func(*Response, error) bool

RetryConditionFunc type is for retry condition function input: non-nil Response OR request execution error

type SRVRecord

type SRVRecord struct {
	Service string
	Domain  string
}

SRVRecord struct holds the data to query the SRV record for the following service.

type SuccessHook

type SuccessHook func(*Client, *Response)

SuccessHook type is for reacting to request success

type TraceInfo

type TraceInfo struct {
	// DNSLookup is a duration that transport took to perform
	// DNS lookup.
	DNSLookup time.Duration

	// ConnTime is a duration that took to obtain a successful connection.
	ConnTime time.Duration

	// TCPConnTime is a duration that took to obtain the TCP connection.
	TCPConnTime time.Duration

	// TLSHandshake is a duration that TLS handshake took place.
	TLSHandshake time.Duration

	// ServerTime is a duration that server took to respond first byte.
	ServerTime time.Duration

	// ResponseTime is a duration since first response byte from server to
	// request completion.
	ResponseTime time.Duration

	// TotalTime is a duration that total request took 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 a duration how long the connection 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 provide request trace info such as DNS lookup duration, Connection obtain duration, Server processing duration, etc.

Since v2.0.0

type User

type User struct {
	Username, Password string
}

User type is to hold an username and password information

Directories

Path Synopsis
examples
Package shellescape provides the shellescape.Quote to escape arbitrary strings for a safe use as command line arguments in the most common POSIX shells.
Package shellescape provides the shellescape.Quote to escape arbitrary strings for a safe use as command line arguments in the most common POSIX shells.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL