Documentation ¶
Overview ¶
Package resty provides Simple HTTP and REST client library for Go.
Example (ClientCertificates) ¶
package main import ( "crypto/tls" "log" "github.com/artpar/resty" ) func main() { // Parsing public/private key pair from a pair of files. The files must contain PEM encoded data. cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key") if err != nil { log.Fatalf("ERROR client certificate: %s", err) } // Create a resty client client := resty.New() client.SetCertificates(cert) }
Output:
Example (CustomRootCertificate) ¶
package main import ( "github.com/artpar/resty" ) func main() { // Create a resty client client := resty.New() client.SetRootCertificate("/path/to/root/pemFile.pem") }
Output:
Example (DropboxUpload) ¶
package main import ( "fmt" "io/ioutil" "os" "github.com/artpar/resty" ) type DropboxError struct { Error string } func main() { // For example: upload file to Dropbox // POST of raw bytes for file upload. file, _ := os.Open("/Users/jeeva/mydocument.pdf") fileBytes, _ := ioutil.ReadAll(file) // Create a resty client client := resty.New() // See we are not setting content-type header, since go-resty automatically detects Content-Type for you resp, err := client.R(). SetBody(fileBytes). // resty autodetects content type SetContentLength(true). // Dropbox expects this value SetAuthToken("<your-auth-token>"). SetError(DropboxError{}). Post("https://content.dropboxapi.com/1/files_put/auto/resty/mydocument.pdf") // you can use PUT method too dropbox supports it // Output print fmt.Printf("\nError: %v\n", err) fmt.Printf("Time: %v\n", resp.Time()) fmt.Printf("Body: %v\n", resp) }
Output:
Example (EnhancedGet) ¶
package main import ( "fmt" "strconv" "time" "github.com/artpar/resty" ) func main() { // Create a resty client client := resty.New() resp, err := client.R(). SetQueryParams(map[string]string{ "page_no": "1", "limit": "20", "sort": "name", "order": "asc", "random": strconv.FormatInt(time.Now().Unix(), 10), }). SetHeader("Accept", "application/json"). SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F"). Get("/search_result") printOutput(resp, err) } func printOutput(resp *resty.Response, err error) { fmt.Println(resp, err) }
Output:
Example (Get) ¶
package main import ( "fmt" "github.com/artpar/resty" ) func main() { // Create a resty client client := resty.New() resp, err := client.R().Get("http://httpbin.org/get") fmt.Printf("\nError: %v", err) fmt.Printf("\nResponse Status Code: %v", resp.StatusCode()) fmt.Printf("\nResponse Status: %v", resp.Status()) fmt.Printf("\nResponse Body: %v", resp) fmt.Printf("\nResponse Time: %v", resp.Time()) fmt.Printf("\nResponse Received At: %v", resp.ReceivedAt()) }
Output:
Example (Post) ¶
package main import ( "fmt" "github.com/artpar/resty" ) type AuthSuccess struct { } type AuthError struct { } func main() { // Create a resty client client := resty.New() // POST JSON string // No need to set content type, if you have client level setting resp, err := client.R(). SetHeader("Content-Type", "application/json"). SetBody(`{"username":"testuser", "password":"testpass"}`). SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}). Post("https://myapp.com/login") printOutput(resp, err) // POST []byte array // No need to set content type, if you have client level setting resp1, err1 := client.R(). SetHeader("Content-Type", "application/json"). SetBody([]byte(`{"username":"testuser", "password":"testpass"}`)). SetResult(AuthSuccess{}). // or SetResult(&AuthSuccess{}). Post("https://myapp.com/login") printOutput(resp1, err1) // POST Struct, default is JSON content type. No need to set one resp2, err2 := client.R(). SetBody(resty.User{Username: "testuser", Password: "testpass"}). SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). SetError(&AuthError{}). // or SetError(AuthError{}). Post("https://myapp.com/login") printOutput(resp2, err2) // POST Map, default is JSON content type. No need to set one resp3, err3 := client.R(). SetBody(map[string]interface{}{"username": "testuser", "password": "testpass"}). SetResult(&AuthSuccess{}). // or SetResult(AuthSuccess{}). SetError(&AuthError{}). // or SetError(AuthError{}). Post("https://myapp.com/login") printOutput(resp3, err3) } func printOutput(resp *resty.Response, err error) { fmt.Println(resp, err) }
Output:
Example (Put) ¶
package main import ( "fmt" "github.com/artpar/resty" ) type Article struct { Title string Content string Author string Tags []string } type Error struct { } func main() { // Create a resty client client := resty.New() // Just one sample of PUT, refer POST for more combination // request goes as JSON content type // No need to set auth token, error, if you have client level settings resp, err := client.R(). SetBody(Article{ Title: "go-resty", Content: "This is my article content, oh ya!", Author: "Jeevanandam M", Tags: []string{"article", "sample", "resty"}, }). SetAuthToken("C6A79608-782F-4ED0-A11D-BD82FAD829CD"). SetError(&Error{}). // or SetError(Error{}). Put("https://myapp.com/article/1234") printOutput(resp, err) } func printOutput(resp *resty.Response, err error) { fmt.Println(resp, err) }
Output:
Example (Socks5Proxy) ¶
package main import ( "fmt" "log" "net/http" "golang.org/x/net/proxy" "github.com/artpar/resty" ) func main() { // create a dialer dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:9150", nil, proxy.Direct) if err != nil { log.Fatalf("Unable to obtain proxy dialer: %v\n", err) } // create a transport ptransport := &http.Transport{Dial: dialer.Dial} // Create a resty client client := resty.New() // set transport into resty client.SetTransport(ptransport) resp, err := client.R().Get("http://check.torproject.org") fmt.Println(err, resp) }
Output:
Index ¶
- Constants
- func Backoff(operation func() (*Response, error), options ...Option) error
- func DetectContentType(body interface{}) string
- func IsJSONType(ct string) bool
- func IsStringEmpty(str string) bool
- func IsXMLType(ct string) bool
- func Unmarshalc(c *Client, ct string, b []byte, d interface{}) (err error)
- type Client
- func (c *Client) AddRetryCondition(condition RetryConditionFunc) *Client
- func (c *Client) DisableTrace() *Client
- func (c *Client) EnableTrace() *Client
- func (c *Client) GetClient() *http.Client
- func (c *Client) IsProxySet() bool
- 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) 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) SetLogger(l Logger) *Client
- func (c *Client) SetOutputDirectory(dirPath string) *Client
- func (c *Client) SetPathParams(params map[string]string) *Client
- func (c *Client) SetPreRequestHook(h func(*Client, *http.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) SetRedirectPolicy(policies ...interface{}) *Client
- func (c *Client) SetRetryAfter(callback RetryAfterFunc) *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) SetRootCertificateFromString(pemContent 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 Logger
- 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) EnableTrace() *Request
- 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) Send() (*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) SetCookie(hc *http.Cookie) *Request
- func (r *Request) SetCookies(rs []*http.Cookie) *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) SetFormDataFromValues(data url.Values) *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) 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) SetQueryParamsFromValues(params url.Values) *Request
- func (r *Request) SetQueryString(query string) *Request
- func (r *Request) SetResult(res interface{}) *Request
- func (r *Request) SetSRV(srv *SRVRecord) *Request
- func (r *Request) TraceInfo() TraceInfo
- 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 RetryAfterFunc
- type RetryConditionFunc
- type SRVRecord
- type TraceInfo
- type User
Examples ¶
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 = "2.2.0"
Version # of resty
Variables ¶
This section is empty.
Functions ¶
func Backoff ¶ added in v1.0.1
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 ¶
IsJSONType method is to check JSON content type or not
func IsStringEmpty ¶
IsStringEmpty method tells whether given string is empty or not
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 RetryCount int RetryWaitTime time.Duration RetryMaxWaitTime time.Duration RetryConditions []RetryConditionFunc RetryAfter RetryAfterFunc JSONMarshal func(v interface{}) ([]byte, error) JSONUnmarshal func(data []byte, v interface{}) error // 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.
Example ¶
package main import ( "fmt" "github.com/artpar/resty" ) func main() { // Creating client1 client1 := resty.New() resp1, err1 := client1.R().Get("http://httpbin.org/get") fmt.Println(resp1, err1) // Creating client2 client2 := resty.New() resp2, err2 := client2.R().Get("http://httpbin.org/get") fmt.Println(resp2, err2) }
Output:
func NewWithClient ¶ added in v1.0.1
NewWithClient method creates a new Resty client with given `http.Client`.
func NewWithLocalAddr ¶ added in v1.0.3
NewWithLocalAddr method creates a new Resty client with given Local Address to dial from.
func (*Client) AddRetryCondition ¶ added in v1.0.1
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) DisableTrace ¶ added in v1.0.3
DisableTrace method disables the Resty client trace. Refer to `Client.EnableTrace`.
Since v2.0.0
func (*Client) EnableTrace ¶ added in v1.0.3
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 ¶ added in v1.0.1
GetClient method returns the current `http.Client` used by the resty client.
func (*Client) IsProxySet ¶ added in v1.0.1
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 ¶ added in v1.0.1
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 ¶
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 assigened 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 ¶
OnBeforeRequest method appends request middleware into the before request chain. Its gets applied after default Resty request middlewares and before request been sent from Resty to 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) OnRequestLog ¶ added in v1.0.3
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 ¶ added in v1.0.3
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 new request instance, its used for Get, Post, Put, Delete, Patch, Head, Options, etc.
func (*Client) RemoveProxy ¶
RemoveProxy method removes the proxy configuration from Resty client
client.RemoveProxy()
func (*Client) SetAllowGetMethodPayload ¶ added in v1.0.1
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) SetAuthToken ¶
SetAuthToken method sets bearer auth token header in the HTTP request. For Example:
Authorization: Bearer <auth-token-value-comes-here>
For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
client.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 `Request.SetAuthToken`.
func (*Client) SetBasicAuth ¶
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 rasied from this client instance. Also it can be overridden or set one at the request level is supported.
See `Request.SetBasicAuth`.
func (*Client) SetCertificates ¶ added in v0.4.1
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
SetCertificates method helps to set client certificates into Resty conveniently.
Example ¶
package main import ( "crypto/tls" "log" "github.com/artpar/resty" ) func main() { // Parsing public/private key pair from a pair of files. The files must contain PEM encoded data. cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key") if err != nil { log.Fatalf("ERROR client certificate: %s", err) } // Create a resty client client := resty.New() client.SetCertificates(cert) }
Output:
func (*Client) SetCloseConnection ¶ added in v1.0.1
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 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 ¶
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 ¶ added in v1.0.1
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 ¶
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 ¶
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)
func (*Client) SetDebugBodyLimit ¶ added in v1.0.1
SetDebugBodyLimit sets the maximum size for which the response and request body will be logged in debug mode.
client.SetDebugBodyLimit(1000000)
func (*Client) SetDisableWarn ¶ added in v1.0.1
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 ¶ added in v1.0.1
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 ¶
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 ¶
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 `Request.SetFormData`.
client.SetFormData(map[string]string{ "access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F", "user_id": "3455454545", })
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 `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) 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 `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 ¶
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")
func (*Client) SetJSONEscapeHTML ¶ added in v1.0.3
SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal.
Note: This option only applicable to standard JSON Marshaller.
func (*Client) SetLogger ¶
SetLogger method sets given writer for logging Resty request and response details.
Compliant to interface `resty.Logger`.
func (*Client) SetOutputDirectory ¶ added in v0.4.1
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) SetPathParams ¶ added in v1.0.3
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", }) 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 ¶ added in v1.0.1
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 mutilple.
func (*Client) SetProxy ¶
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 ¶
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 ¶
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) SetRedirectPolicy ¶
SetRedirectPolicy method sets the client redirect poilicy. 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) SetRetryAfter ¶ added in v1.0.3
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 ¶ added in v1.0.1
SetRetryCount method enables retry on Resty client and allows you to set no. of retry count. Resty uses a Backoff mechanism.
func (*Client) SetRetryMaxWaitTime ¶ added in v1.0.1
SetRetryMaxWaitTime method sets max wait time to sleep before retrying request.
Default is 2 seconds.
func (*Client) SetRetryWaitTime ¶ added in v1.0.1
SetRetryWaitTime method sets default wait time to sleep before retrying request.
Default is 100 milliseconds.
func (*Client) SetRootCertificate ¶ added in v0.4.1
SetRootCertificate method helps to add one or more root certificates into Resty client
client.SetRootCertificate("/path/to/root/pemFile.pem")
func (*Client) SetRootCertificateFromString ¶ added in v1.0.3
SetRootCertificateFromString method helps to add one or more root certificates into Resty client
client.SetRootCertificateFromString("pem file content")
func (*Client) SetScheme ¶ added in v1.0.1
SetScheme method sets custom scheme in the Resty client. It's way to override default.
client.SetScheme("http")
func (*Client) SetTLSClientConfig ¶
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 ¶
SetTimeout method sets timeout for request raised from client.
client.SetTimeout(time.Duration(1 * time.Minute))
func (*Client) SetTransport ¶ added in v1.0.1
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) }, } client.SetTransport(transport)
type Logger ¶ added in v1.0.3
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 ¶ added in v1.0.3
MultipartField struct represent custom data part for multipart request
type Option ¶ added in v1.0.1
type Option func(*Options)
Option is to create convenient retry options like wait time, max retries, etc.
func MaxWaitTime ¶ added in v1.0.1
MaxWaitTime sets the max wait time to sleep between requests
func RetryConditions ¶ added in v1.0.1
func RetryConditions(conditions []RetryConditionFunc) Option
RetryConditions sets the conditions that will be checked for retry.
type Options ¶ added in v1.0.1
type Options struct {
// contains filtered or unexported fields
}
Options struct is used to hold retry settings.
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 Cookies []*http.Cookie // 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) Context ¶ added in v1.0.3
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) EnableTrace ¶ added in v1.0.3
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 ¶ added in v0.4.1
Execute method performs the HTTP request with given HTTP method and URL for current `Request`.
resp, err := client.R().Execute(resty.GET, "http://httpbin.org/get")
func (*Request) ExpectContentType ¶ added in v1.0.1
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) Send ¶ added in v1.0.3
Send method performs the HTTP request using the method and URL already defined for current `Request`.
req := client.R() req.Method = resty.GET req.URL = "http://httpbin.org/get" resp, err := client.R().Send()
func (*Request) SetAuthToken ¶
SetAuthToken method sets bearer auth token header 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 ¶
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 ¶
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 ¶
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 ¶ added in v1.0.1
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 ¶ added in v1.0.3
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 ¶ added in v1.0.3
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) SetDoNotParseResponse ¶ added in v1.0.1
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 ¶
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 ¶
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 ¶ added in v1.0.1
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 ¶
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 ¶
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 ¶ added in v1.0.3
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 ¶
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) SetHeaders ¶
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 ¶ added in v1.0.3
SetJSONEscapeHTML method is to enable/disable the HTML escape on JSON marshal.
Note: This option only applicable to standard JSON Marshaller.
func (*Request) SetMultipartField ¶ added in v1.0.3
SetMultipartField method is to set custom data using io.Reader for multipart upload.
func (*Request) SetMultipartFields ¶ added in v1.0.3
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) SetOutput ¶ added in v0.4.1
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) SetPathParams ¶ added in v1.0.3
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", }) 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.
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 ¶
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 ¶ added in v1.0.3
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 ¶ added in v0.4.1
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) SetResult ¶
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 ¶ added in v1.0.1
SetSRV method sets the details to query the service SRV record and execute the request.
client.R(). SetSRV(SRVRecord{"web", "testservice.com"}). Get("/get")
type RequestLog ¶ added in v1.0.3
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 struct holds response values of executed request.
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) IsError ¶ added in v1.0.3
IsError method returns true if HTTP status `code >= 400` otherwise false.
func (*Response) IsSuccess ¶ added in v1.0.3
IsSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.
func (*Response) RawBody ¶ added in v1.0.1
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 ¶ added in v0.4.1
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 ¶ added in v1.0.3
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 RetryAfterFunc ¶ added in v1.0.3
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 ¶ added in v1.0.1
RetryConditionFunc type is for retry condition function input: non-nil Response OR request execution error
type SRVRecord ¶ added in v1.0.1
SRVRecord struct holds the data to query the SRV record for the following service.
type TraceInfo ¶ added in v1.0.3
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 // 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 }
TraceInfo struct is used provide request trace info such as DNS lookup duration, Connection obtain duration, Server processing duration, etc.
Since v2.0.0