Documentation ¶
Overview ¶
Package resty provides Simple HTTP and REST client library for Go.
Index ¶
- Constants
- func Backoff(operation func() (*Response, error), options ...Option) error
- func DetectContentType(body interface{}) string
- func GetClient() *http.Client
- func IsJSONType(ct string) bool
- func IsProxySet() bool
- func IsStringEmpty(str string) bool
- func IsXMLType(ct string) bool
- func Mode() string
- func Unmarshal(ct string, b []byte, d interface{}) (err error)
- func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error)
- type Client
- func AddRetryCondition(condition RetryConditionFunc) *Client
- func New() *Client
- func NewWithClient(hc *http.Client) *Client
- func OnAfterResponse(m func(*Client, *Response) error) *Client
- func OnBeforeRequest(m func(*Client, *Request) error) *Client
- func RemoveProxy() *Client
- func SetAllowGetMethodPayload(a bool) *Client
- func SetAuthToken(token string) *Client
- func SetBasicAuth(username, password string) *Client
- func SetCertificates(certs ...tls.Certificate) *Client
- func SetCloseConnection(close bool) *Client
- func SetContentLength(l bool) *Client
- func SetCookie(hc *http.Cookie) *Client
- func SetCookieJar(jar http.CookieJar) *Client
- func SetCookies(cs []*http.Cookie) *Client
- func SetDebug(d bool) *Client
- func SetDebugBodyLimit(sl int64) *Client
- func SetDisableWarn(d bool) *Client
- func SetDoNotParseResponse(parse bool) *Client
- func SetError(err interface{}) *Client
- func SetFormData(data map[string]string) *Client
- func SetHTTPMode() *Client
- func SetHeader(header, value string) *Client
- func SetHeaders(headers map[string]string) *Client
- func SetHostURL(url string) *Client
- func SetLogger(w io.Writer) *Client
- func SetOutputDirectory(dirPath string) *Client
- func SetPathParams(params map[string]string) *Client
- func SetPreRequestHook(h func(*Client, *Request) error) *Client
- func SetProxy(proxyURL string) *Client
- func SetQueryParam(param, value string) *Client
- func SetQueryParams(params map[string]string) *Client
- func SetRESTMode() *Client
- func SetRedirectPolicy(policies ...interface{}) *Client
- func SetRetryCount(count int) *Client
- func SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client
- func SetRetryWaitTime(waitTime time.Duration) *Client
- func SetRootCertificate(pemFilePath string) *Client
- func SetScheme(scheme string) *Client
- func SetTLSClientConfig(config *tls.Config) *Client
- func SetTimeout(timeout time.Duration) *Client
- func SetTransport(transport http.RoundTripper) *Client
- func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client
- func (c *Client) GetClient() *http.Client
- func (c *Client) IsProxySet() bool
- func (c *Client) Mode() string
- func (c *Client) NewRequest() *Request
- func (c *Client) OnAfterResponse(m func(*Client, *Response) error) *Client
- func (c *Client) OnBeforeRequest(m func(*Client, *Request) error) *Client
- func (c *Client) OnRequestLog(rl func(*RequestLog) error) *Client
- func (c *Client) OnResponseLog(rl func(*ResponseLog) error) *Client
- func (c *Client) R() *Request
- func (c *Client) RemoveProxy() *Client
- func (c *Client) SetAllowGetMethodPayload(a bool) *Client
- func (c *Client) SetAuthToken(token string) *Client
- func (c *Client) SetBasicAuth(username, password string) *Client
- func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
- func (c *Client) SetCloseConnection(close bool) *Client
- func (c *Client) SetContentLength(l bool) *Client
- func (c *Client) SetCookie(hc *http.Cookie) *Client
- func (c *Client) SetCookieJar(jar http.CookieJar) *Client
- func (c *Client) SetCookies(cs []*http.Cookie) *Client
- func (c *Client) SetDebug(d bool) *Client
- func (c *Client) SetDebugBodyLimit(sl int64) *Client
- func (c *Client) SetDisableWarn(d bool) *Client
- func (c *Client) SetDoNotParseResponse(parse bool) *Client
- func (c *Client) SetError(err interface{}) *Client
- func (c *Client) SetFormData(data map[string]string) *Client
- func (c *Client) SetHTTPMode() *Client
- func (c *Client) SetHeader(header, value string) *Client
- func (c *Client) SetHeaders(headers map[string]string) *Client
- func (c *Client) SetHostURL(url string) *Client
- func (c *Client) SetJSONEscapeHTML(b bool) *Client
- func (c *Client) SetLogPrefix(prefix string) *Client
- func (c *Client) SetLogger(w io.Writer) *Client
- func (c *Client) SetMode(mode string) *Client
- func (c *Client) SetOutputDirectory(dirPath string) *Client
- func (c *Client) SetPathParams(params map[string]string) *Client
- func (c *Client) SetPreRequestHook(h func(*Client, *Request) error) *Client
- func (c *Client) SetProxy(proxyURL string) *Client
- func (c *Client) SetQueryParam(param, value string) *Client
- func (c *Client) SetQueryParams(params map[string]string) *Client
- func (c *Client) SetRESTMode() *Client
- func (c *Client) SetRedirectPolicy(policies ...interface{}) *Client
- func (c *Client) SetRetryCount(count int) *Client
- func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client
- func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client
- func (c *Client) SetRootCertificate(pemFilePath string) *Client
- func (c *Client) SetScheme(scheme string) *Client
- func (c *Client) SetTLSClientConfig(config *tls.Config) *Client
- func (c *Client) SetTimeout(timeout time.Duration) *Client
- func (c *Client) SetTransport(transport http.RoundTripper) *Client
- type File
- type MultipartField
- type Option
- type Options
- type RedirectPolicy
- type RedirectPolicyFunc
- type Request
- func (r *Request) Context() context.Context
- func (r *Request) Delete(url string) (*Response, error)
- func (r *Request) Execute(method, url string) (*Response, error)
- func (r *Request) ExpectContentType(contentType string) *Request
- func (r *Request) Get(url string) (*Response, error)
- func (r *Request) Head(url string) (*Response, error)
- func (r *Request) Options(url string) (*Response, error)
- func (r *Request) Patch(url string) (*Response, error)
- func (r *Request) Post(url string) (*Response, error)
- func (r *Request) Put(url string) (*Response, error)
- func (r *Request) SetAuthToken(token string) *Request
- func (r *Request) SetBasicAuth(username, password string) *Request
- func (r *Request) SetBody(body interface{}) *Request
- func (r *Request) SetContentLength(l bool) *Request
- func (r *Request) SetContext(ctx context.Context) *Request
- func (r *Request) SetDoNotParseResponse(parse bool) *Request
- func (r *Request) SetError(err interface{}) *Request
- func (r *Request) SetFile(param, filePath string) *Request
- func (r *Request) SetFileReader(param, fileName string, reader io.Reader) *Request
- func (r *Request) SetFiles(files map[string]string) *Request
- func (r *Request) SetFormData(data map[string]string) *Request
- func (r *Request) SetHeader(header, value string) *Request
- func (r *Request) SetHeaders(headers map[string]string) *Request
- func (r *Request) SetJSONEscapeHTML(b bool) *Request
- func (r *Request) SetMultiValueFormData(params url.Values) *Request
- func (r *Request) SetMultiValueQueryParams(params url.Values) *Request
- func (r *Request) SetMultipartField(param, fileName, contentType string, reader io.Reader) *Request
- func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request
- func (r *Request) SetOutput(file string) *Request
- func (r *Request) SetPathParams(params map[string]string) *Request
- func (r *Request) SetQueryParam(param, value string) *Request
- func (r *Request) SetQueryParams(params map[string]string) *Request
- func (r *Request) SetQueryString(query string) *Request
- func (r *Request) SetResult(res interface{}) *Request
- func (r *Request) SetSRV(srv *SRVRecord) *Request
- type RequestLog
- type Response
- func (r *Response) Body() []byte
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Error() interface{}
- func (r *Response) Header() http.Header
- func (r *Response) IsError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) RawBody() io.ReadCloser
- func (r *Response) ReceivedAt() time.Time
- func (r *Response) Result() interface{}
- func (r *Response) Size() int64
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- func (r *Response) String() string
- func (r *Response) Time() time.Duration
- type ResponseLog
- type RetryConditionFunc
- type SRVRecord
- type User
Constants ¶
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" )
const Version = "1.12.0"
Version # of resty
Variables ¶
This section is empty.
Functions ¶
func Backoff ¶
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 GetClient ¶
GetClient method returns the current `http.Client` used by the default resty client.
func IsJSONType ¶
IsJSONType method is to check JSON content type or not
func IsProxySet ¶
func IsProxySet() bool
IsProxySet method returns the true if proxy is set on client otherwise false. See `Client.IsProxySet` for more information.
func IsStringEmpty ¶
IsStringEmpty method tells whether given string is empty or not
func Mode ¶
func Mode() string
Mode method returns the current client mode. See `Client.Mode` for more information.
Types ¶
type Client ¶
type Client struct { HostURL string QueryParam url.Values FormData url.Values Header http.Header UserInfo *User Token string Cookies []*http.Cookie Error reflect.Type Debug bool DisableWarn bool AllowGetMethodPayload bool Log *log.Logger RetryCount int RetryWaitTime time.Duration RetryMaxWaitTime time.Duration RetryConditions []RetryConditionFunc JSONMarshal func(v interface{}) ([]byte, error) JSONUnmarshal func(data []byte, v interface{}) error // contains filtered or unexported fields }
Client type is used for HTTP/RESTful global values for all request raised from the client
var DefaultClient *Client
DefaultClient of resty
func AddRetryCondition ¶
func AddRetryCondition(condition RetryConditionFunc) *Client
AddRetryCondition method appends check function for retry. See `Client.AddRetryCondition` for more information.
func NewWithClient ¶
NewWithClient method create a new go-resty client with given `http.Client`.
func OnAfterResponse ¶
OnAfterResponse method sets response middleware. See `Client.OnAfterResponse` for more information.
func OnBeforeRequest ¶
OnBeforeRequest method sets request middleware. See `Client.OnBeforeRequest` for more information.
func RemoveProxy ¶
func RemoveProxy() *Client
RemoveProxy method removes the proxy configuration. See `Client.RemoveProxy` for more information.
func SetAllowGetMethodPayload ¶
SetAllowGetMethodPayload method allows the GET method with payload. See `Client.SetAllowGetMethodPayload` for more information.
func SetAuthToken ¶
SetAuthToken method sets bearer auth token header. See `Client.SetAuthToken` for more information.
func SetBasicAuth ¶
SetBasicAuth method sets the basic authentication header. See `Client.SetBasicAuth` for more information.
func SetCertificates ¶
func SetCertificates(certs ...tls.Certificate) *Client
SetCertificates method helps to set client certificates into resty conveniently. See `Client.SetCertificates` for more information and example.
func SetCloseConnection ¶
SetCloseConnection method sets close connection value in the resty client. See `Client.SetCloseConnection` for more information.
func SetContentLength ¶
SetContentLength method enables `Content-Length` value. See `Client.SetContentLength` for more information.
func SetCookieJar ¶
SetCookieJar sets custom http.CookieJar. See `Client.SetCookieJar` for more information.
func SetCookies ¶
SetCookies sets multiple cookie object. See `Client.SetCookies` for more information.
func SetDebug ¶
SetDebug method enables the debug mode. See `Client.SetDebug` for more information.
func SetDebugBodyLimit ¶
SetDebugBodyLimit method sets the response body limit for debug mode. See `Client.SetDebugBodyLimit` for more information.
func SetDisableWarn ¶
SetDisableWarn method disables warning comes from `go-resty` client. See `Client.SetDisableWarn` for more information.
func SetDoNotParseResponse ¶
SetDoNotParseResponse method instructs `Resty` not to parse the response body automatically. See `Client.SetDoNotParseResponse` for more information.
func SetError ¶
func SetError(err interface{}) *Client
SetError method is to register the global or client common `Error` object. See `Client.SetError` for more information.
func SetFormData ¶
SetFormData method sets Form parameters and its values. See `Client.SetFormData` for more information.
func SetHTTPMode ¶
func SetHTTPMode() *Client
SetHTTPMode method sets go-resty mode into HTTP. See `Client.SetMode` for more information.
func SetHeaders ¶
SetHeaders sets multiple headers. See `Client.SetHeaders` for more information.
func SetHostURL ¶
SetHostURL sets Host URL. See `Client.SetHostURL for more information.
func SetLogger ¶
SetLogger method sets given writer for logging. See `Client.SetLogger` for more information.
func SetOutputDirectory ¶
SetOutputDirectory method sets output directory. See `Client.SetOutputDirectory` for more information.
func SetPathParams ¶
SetPathParams method sets the Request path parameter key-value pairs. See `Client.SetPathParams` for more information.
func SetPreRequestHook ¶
SetPreRequestHook method sets the pre-request hook. See `Client.SetPreRequestHook` for more information.
func SetProxy ¶
SetProxy method sets Proxy for request. See `Client.SetProxy` for more information.
func SetQueryParam ¶
SetQueryParam method sets single parameter and its value. See `Client.SetQueryParam` for more information.
func SetQueryParams ¶
SetQueryParams method sets multiple parameters and its value. See `Client.SetQueryParams` for more information.
func SetRESTMode ¶
func SetRESTMode() *Client
SetRESTMode method sets go-resty mode into RESTful. See `Client.SetMode` for more information.
func SetRedirectPolicy ¶
func SetRedirectPolicy(policies ...interface{}) *Client
SetRedirectPolicy method sets the client redirect poilicy. See `Client.SetRedirectPolicy` for more information.
func SetRetryCount ¶
SetRetryCount method sets the retry count. See `Client.SetRetryCount` for more information.
func SetRetryMaxWaitTime ¶
SetRetryMaxWaitTime method sets the retry max wait time. See `Client.SetRetryMaxWaitTime` for more information.
func SetRetryWaitTime ¶
SetRetryWaitTime method sets the retry wait time. See `Client.SetRetryWaitTime` for more information.
func SetRootCertificate ¶
SetRootCertificate method helps to add one or more root certificates into resty client. See `Client.SetRootCertificate` for more information.
func SetScheme ¶
SetScheme method sets custom scheme in the resty client. See `Client.SetScheme` for more information.
func SetTLSClientConfig ¶
SetTLSClientConfig method sets TLSClientConfig for underling client Transport. See `Client.SetTLSClientConfig` for more information.
func SetTimeout ¶
SetTimeout method sets timeout for request. See `Client.SetTimeout` for more information.
func SetTransport ¶
func SetTransport(transport http.RoundTripper) *Client
SetTransport method sets custom `*http.Transport` or any `http.RoundTripper` compatible interface implementation in the resty client. See `Client.SetTransport` for more information.
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.
func (*Client) GetClient ¶
GetClient method returns the current http.Client used by the resty client.
func (*Client) IsProxySet ¶
IsProxySet method returns the true if proxy is set on client otherwise false.
func (*Client) Mode ¶
Mode method returns the current client mode. Typically its a "http" or "rest". Default is "rest"
func (*Client) NewRequest ¶
NewRequest is an alias for R(). Creates a request instance, its used for Get, Post, Put, Delete, Patch, Head and Options.
func (*Client) OnAfterResponse ¶
OnAfterResponse method appends response middleware into the after response chain. Once we receive response from host server, default `go-resty` response middleware gets applied and then user assigened response middlewares applied.
resty.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 ¶
OnBeforeRequest method appends request middleware into the before request chain. Its gets applied after default `go-resty` request middlewares and before request been sent from `go-resty` to host server.
resty.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) OnRequestLog ¶
func (c *Client) OnRequestLog(rl func(*RequestLog) error) *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 func(*ResponseLog) error) *Client
OnResponseLog method used to set response log callback into resty. Registered callback gets called before the resty actually logs the information.
func (*Client) R ¶
R method creates a request instance, its used for Get, Post, Put, Delete, Patch, Head and Options.
func (*Client) RemoveProxy ¶
RemoveProxy method removes the proxy configuration from resty client
resty.RemoveProxy()
func (*Client) SetAllowGetMethodPayload ¶
SetAllowGetMethodPayload method allows the GET method with payload on `go-resty` client. For example: go-resty allows the user sends request with a payload on HTTP GET method.
resty.SetAllowGetMethodPayload(true)
func (*Client) SetAuthToken ¶
SetAuthToken method sets bearer auth token header in the HTTP request. Example:
Authorization: Bearer <auth-token-value-comes-here>
Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
resty.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
This bearer auth token gets added to all the request rasied from this client instance. Also it can be overridden or set one at the request level is supported, see `resty.R().SetAuthToken`.
func (*Client) SetBasicAuth ¶
SetBasicAuth method sets the basic authentication header in the HTTP request. Example:
Authorization: Basic <base64-encoded-value>
Example: To set the header for username "go-resty" and password "welcome"
resty.SetBasicAuth("go-resty", "welcome")
This basic auth information gets added to all the request rasied from this client instance. Also it can be overridden or set one at the request level is supported, see `resty.R().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 ¶
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 ¶
SetContentLength method enables the HTTP header `Content-Length` value for every request. By default go-resty won't set `Content-Length`.
resty.SetContentLength(true)
Also you have an option to enable for particular request. See `resty.R().SetContentLength`
func (*Client) SetCookie ¶
SetCookie method appends a single cookie in the client instance. These cookies will be added to all the request raised from this client instance.
resty.SetCookie(&http.Cookie{ Name:"go-resty", Value:"This is cookie value", Path: "/", Domain: "sample.com", MaxAge: 36000, HttpOnly: true, Secure: false, })
func (*Client) SetCookieJar ¶
SetCookieJar method sets custom http.CookieJar in the resty client. Its way to override default. Example: sometimes we don't want to save cookies in api contacting, we can remove the default CookieJar in resty client.
resty.SetCookieJar(nil)
func (*Client) SetCookies ¶
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 := make([]*http.Cookie, 0) cookies = append(cookies, &http.Cookie{ Name:"go-resty-1", Value:"This is cookie 1 value", Path: "/", Domain: "sample.com", MaxAge: 36000, HttpOnly: true, Secure: false, }) cookies = append(cookies, &http.Cookie{ Name:"go-resty-2", Value:"This is cookie 2 value", Path: "/", Domain: "sample.com", MaxAge: 36000, HttpOnly: true, Secure: false, }) // Setting a cookies into resty resty.SetCookies(cookies)
func (*Client) SetDebug ¶
SetDebug method enables the debug mode on `go-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.
resty.SetDebug(true)
func (*Client) SetDebugBodyLimit ¶
SetDebugBodyLimit sets the maximum size for which the response body will be logged in debug mode.
resty.SetDebugBodyLimit(1000000)
func (*Client) SetDisableWarn ¶
SetDisableWarn method disables the warning message on `go-resty` client. For example: go-resty warns the user when BasicAuth used on HTTP mode.
resty.SetDisableWarn(true)
func (*Client) SetDoNotParseResponse ¶
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.
Please 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 ¶
SetError method is to register the global or client common `Error` object into go-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.
resty.SetError(&Error{}) // OR resty.SetError(Error{})
func (*Client) SetFormData ¶
SetFormData method sets Form parameters and their values in the client instance. It's applicable only HTTP method `POST` and `PUT` and requets 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 `resty.R().SetFormData`.
resty.SetFormData(map[string]string{ "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", "user_id": "3455454545", })
func (*Client) SetHTTPMode ¶
SetHTTPMode method sets go-resty mode to 'http'
func (*Client) SetHeader ¶
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 `resty.R().SetHeader` or `resty.R().SetHeaders`.
Example: To set `Content-Type` and `Accept` as `application/json`
resty. SetHeader("Content-Type", "application/json"). SetHeader("Accept", "application/json")
func (*Client) SetHeaders ¶
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 `resty.R().SetHeaders` or `resty.R().SetHeader`.
Example: To set `Content-Type` and `Accept` as `application/json`
resty.SetHeaders(map[string]string{ "Content-Type": "application/json", "Accept": "application/json", })
func (*Client) SetHostURL ¶
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 resty.SetHostURL("http://myjeeva.com") // Setting HTTPS address resty.SetHostURL("https://myjeeva.com")
func (*Client) SetJSONEscapeHTML ¶
SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal.
NOTE: This option only applicable to standard JSON Marshaller.
func (*Client) SetLogPrefix ¶
SetLogPrefix method sets the Resty logger prefix value.
func (*Client) SetLogger ¶
SetLogger method sets given writer for logging go-resty request and response details. Default is os.Stderr
file, _ := os.OpenFile("/Users/jeeva/go-resty.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) resty.SetLogger(file)
func (*Client) SetMode ¶
SetMode method sets go-resty client mode to given value such as 'http' & 'rest'.
'rest': - No Redirect - Automatic response unmarshal if it is JSON or XML 'http': - Up to 10 Redirects - No automatic unmarshall. Response will be treated as `response.String()`
If you want more redirects, use FlexibleRedirectPolicy
resty.SetRedirectPolicy(FlexibleRedirectPolicy(20))
func (*Client) SetOutputDirectory ¶
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 absoule path in `Request.SetOutput` and can used together.
resty.SetOutputDirectory("/save/http/response/here")
func (*Client) SetPathParams ¶
SetPathParams method sets multiple URL path key-value pairs at one go in the resty client instance.
resty.SetPathParams(map[string]string{ "userId": "sample@sample.com", "subAccountId": "100002", }) Result: URL - /v1/users/{userId}/{subAccountId}/details Composed URL - /v1/users/sample@sample.com/100002/details
It replace the value of the key while composing request URL. Also it can be overridden at request level Path Params options, see `Request.SetPathParams`.
func (*Client) SetPreRequestHook ¶
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 `resty.OnBeforeRequest` for mutilple.
func (*Client) SetProxy ¶
SetProxy method sets the Proxy URL and Port for resty client.
resty.SetProxy("http://proxyserver:8888")
Alternatives: At request level proxy, see `Request.SetProxy`. OR Without this `SetProxy` method, you can also set Proxy via environment variable. By default `Go` uses setting from `HTTP_PROXY`.
func (*Client) SetQueryParam ¶
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 `resty.R().SetQueryParam` or `resty.R().SetQueryParams`.
resty. SetQueryParam("search", "kitchen papers"). SetQueryParam("size", "large")
func (*Client) SetQueryParams ¶
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 `resty.R().SetQueryParams` or `resty.R().SetQueryParam`.
resty.SetQueryParams(map[string]string{ "search": "kitchen papers", "size": "large", })
func (*Client) SetRESTMode ¶
SetRESTMode method sets go-resty mode to 'rest'
func (*Client) SetRedirectPolicy ¶
SetRedirectPolicy method sets the client redirect poilicy. go-resty provides ready to use redirect policies. Wanna create one for yourself refer `redirect.go`.
resty.SetRedirectPolicy(FlexibleRedirectPolicy(20)) // Need multiple redirect policies together resty.SetRedirectPolicy(FlexibleRedirectPolicy(20), DomainCheckRedirectPolicy("host1.com", "host2.net"))
func (*Client) SetRetryCount ¶
SetRetryCount method enables retry on `go-resty` client and allows you to set no. of retry count. Resty uses a Backoff mechanism.
func (*Client) SetRetryMaxWaitTime ¶
SetRetryMaxWaitTime method sets max wait time to sleep before retrying request. Default is 2 seconds.
func (*Client) SetRetryWaitTime ¶
SetRetryWaitTime method sets default wait time to sleep before retrying request. Default is 100 milliseconds.
func (*Client) SetRootCertificate ¶
SetRootCertificate method helps to add one or more root certificates into resty client
resty.SetRootCertificate("/path/to/root/pemFile.pem")
func (*Client) SetScheme ¶
SetScheme method sets custom scheme in the resty client. It's way to override default.
resty.SetScheme("http")
func (*Client) SetTLSClientConfig ¶
SetTLSClientConfig method sets TLSClientConfig for underling client Transport.
Example:
// One can set custom root-certificate. Refer: http://golang.org/pkg/crypto/tls/#example_Dial resty.SetTLSClientConfig(&tls.Config{ RootCAs: roots }) // or One can disable security check (https) resty.SetTLSClientConfig(&tls.Config{ InsecureSkipVerify: true })
Note: This method overwrites existing `TLSClientConfig`.
func (*Client) SetTimeout ¶
SetTimeout method sets timeout for request raised from client.
resty.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{ // somthing like Proxying to httptest.Server, etc... Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL) }, } resty.SetTransport(transport)
type MultipartField ¶
MultipartField represent custom data part for multipart request
type Option ¶
type Option func(*Options)
Option is to create convenient retry options like wait time, max retries, etc.
func MaxWaitTime ¶
MaxWaitTime sets the max wait time to sleep between requests
func RetryConditions ¶
func RetryConditions(conditions []RetryConditionFunc) Option
RetryConditions sets the conditions that will be checked for retry.
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options to hold go-resty retry values
type RedirectPolicy ¶
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 jounery, 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 ¶
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.
type Request ¶
type Request struct { URL string Method string Token string QueryParam url.Values FormData url.Values Header http.Header Time time.Time Body interface{} Result interface{} Error interface{} RawRequest *http.Request SRV *SRVRecord UserInfo *User // contains filtered or unexported fields }
Request type is used to compose and send individual request from client go-resty is provide option override client level settings such as Auth Token, Basic Auth credentials, Header, Query Param, Form Data, Error object and also you can add more options for that particular request
func NewRequest ¶
func NewRequest() *Request
NewRequest is an alias for R(). Creates a new resty request object, it is used form a HTTP/RESTful request such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.
func R ¶
func R() *Request
R creates a new resty request object, it is used form a HTTP/RESTful request such as GET, POST, PUT, DELETE, HEAD, PATCH and OPTIONS.
func (*Request) Context ¶
Context method returns the Context if its already set in request otherwise it creates new one using `context.Background()`.
func (*Request) Delete ¶
Delete method does DELETE HTTP request. It's defined in section 4.3.5 of RFC7231.
func (*Request) Execute ¶
Execute method performs the HTTP request with given HTTP method and URL for current `Request`.
resp, err := resty.R().Execute(resty.GET, "http://httpbin.org/get")
func (*Request) ExpectContentType ¶
ExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling when `Content-Type` response header is unavailable.
func (*Request) Head ¶
Head method does HEAD HTTP request. It's defined in section 4.3.2 of RFC7231.
func (*Request) Options ¶
Options method does OPTIONS HTTP request. It's defined in section 4.3.7 of RFC7231.
func (*Request) Patch ¶
Patch method does PATCH HTTP request. It's defined in section 2 of RFC5789.
func (*Request) Post ¶
Post method does POST HTTP request. It's defined in section 4.3.3 of RFC7231.
func (*Request) SetAuthToken ¶
SetAuthToken method sets bearer auth token header in the current HTTP request. Header example:
Authorization: Bearer <auth-token-value-comes-here>
Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
resty.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
This method overrides the Auth token set by method `resty.SetAuthToken`.
func (*Request) SetBasicAuth ¶
SetBasicAuth method sets the basic authentication header in the current HTTP request. For Header example:
Authorization: Basic <base64-encoded-value>
To set the header for username "go-resty" and password "welcome"
resty.R().SetBasicAuth("go-resty", "welcome")
This method overrides the credentials set by method `resty.SetBasicAuth`.
func (*Request) SetBody ¶
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.
Example:
Struct as a body input, based on content type, it will be marshalled.
resty.R(). SetBody(User{ Username: "jeeva@myjeeva.com", Password: "welcome2resty", })
Map as a body input, based on content type, it will be marshalled.
resty.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.
resty.R(). SetBody(`{ "username": "jeeva@getrightcare.com", "password": "admin" }`)
[]byte as a body input. Suitable for raw request such as file upload, serialize & deserialize, etc.
resty.R(). SetBody([]byte("This is my raw request, sent as-is"))
func (*Request) SetContentLength ¶
SetContentLength method sets the HTTP header `Content-Length` value for current request. By default go-resty won't set `Content-Length`. Also you have an option to enable for every request. See `resty.SetContentLength`
resty.R().SetContentLength(true)
func (*Request) SetContext ¶
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) SetDoNotParseResponse ¶
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.
Please 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 ¶
SetError method is to register the request `Error` object for automatic unmarshalling in the RESTful mode if response status code is greater than 399 and content type either JSON or XML.
Note: Error object can be pointer or non-pointer.
resty.R().SetError(&AuthError{}) // OR resty.R().SetError(AuthError{})
Accessing a error value
response.Error().(*AuthError)
func (*Request) SetFile ¶
SetFile method is to set single file field name and its path for multipart upload.
resty.R(). SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf")
func (*Request) SetFileReader ¶
SetFileReader method is to set single file using io.Reader for multipart upload.
resty.R(). SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)). SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes))
func (*Request) SetFiles ¶
SetFiles method is to set multiple file field name and its path for multipart upload.
resty.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 ¶
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`.
resty.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) SetHeader ¶
SetHeader method is to set a single header field and its value in the current request. Example: To set `Content-Type` and `Accept` as `application/json`.
resty.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) SetHeaders ¶
SetHeaders method sets multiple headers field and its values at one go in the current request. Example: To set `Content-Type` and `Accept` as `application/json`
resty.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 ¶
SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal.
NOTE: This option only applicable to standard JSON Marshaller.
func (*Request) SetMultiValueFormData ¶
SetMultiValueFormData method appends multiple form parameters with multi-value at one go in the current request.
resty.R(). SetMultiValueFormData(url.Values{ "search_criteria": []string{"book", "glass", "pencil"}, })
Also you can override form data value, which was set at client instance level
func (*Request) SetMultiValueQueryParams ¶
SetMultiValueQueryParams method appends multiple parameters with multi-value at one go in the current request. It will be formed as query string for the request. Example: `status=pending&status=approved&status=open` in the URL after `?` mark.
resty.R(). SetMultiValueQueryParams(url.Values{ "status": []string{"pending", "approved", "open"}, })
Also you can override query params value, which was set at client instance level
func (*Request) SetMultipartField ¶
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. Example:
resty.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-
resty.R().SetMultipartFields(fields...)
func (*Request) SetOutput ¶
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`.
resty.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) SetPathParams ¶
SetPathParams method sets multiple URL path key-value pairs at one go in the resty current request instance.
resty.R().SetPathParams(map[string]string{ "userId": "sample@sample.com", "subAccountId": "100002", }) Result: URL - /v1/users/{userId}/{subAccountId}/details Composed URL - /v1/users/sample@sample.com/100002/details
It replace the value of the key while composing request URL. Also you can override Path Params value, which was set at client instance level.
func (*Request) SetQueryParam ¶
SetQueryParam method sets single parameter and its value in the current request. It will be formed as query string for the request. Example: `search=kitchen%20papers&size=large` in the URL after `?` mark.
resty.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 ¶
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. Example: `search=kitchen%20papers&size=large` in the URL after `?` mark.
resty.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) SetQueryString ¶
SetQueryString method provides ability to use string as an input to set URL query string for the request.
Using String as an input
resty.R(). SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")
func (*Request) SetResult ¶
SetResult method is to register the response `Result` object for automatic unmarshalling in the RESTful mode 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.
resty.R().SetResult(&AuthToken{}) // OR resty.R().SetResult(AuthToken{})
Accessing a result value
response.Result().(*AuthToken)
type RequestLog ¶
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 Response ¶
type Response struct { Request *Request RawResponse *http.Response // contains filtered or unexported fields }
Response is an object represents executed request and its values.
func (*Response) Body ¶
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) Error ¶
func (r *Response) Error() interface{}
Error method returns the error object if it has one
func (*Response) IsSuccess ¶
IsSuccess method returns true if HTTP status code >= 200 and <= 299 otherwise false.
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 ¶
ReceivedAt method returns when response got recevied 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) Size ¶
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 ¶
Status method returns the HTTP status string for the executed request.
Example: 200 OK
func (*Response) StatusCode ¶
StatusCode method returns the HTTP status code for the executed request.
Example: 200
type ResponseLog ¶
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 RetryConditionFunc ¶
RetryConditionFunc type is for retry condition function