Documentation
¶
Overview ¶
Package resty provides a simple HTTP, REST, and SSE client library for Go.
Index ¶
- Constants
- Variables
- func CircuitBreaker5xxPolicy(resp *Response) bool
- func DebugLogFormatter(dl *DebugLog) string
- func DebugLogJSONFormatter(dl *DebugLog) string
- func MiddlewareRequestCreate(c *Client, r *Request) (err error)
- func MiddlewareResponseAutoParse(c *Client, res *Response) (err error)
- func MiddlewareResponseSaveToFile(c *Client, res *Response) error
- func RetryConditionStatus5XX(res *Response, _ error) bool
- func RetryConditionStatusTooManyRequests(res *Response, _ error) bool
- func RetryConditionStatusZero(res *Response, _ error) bool
- type CertWatcherOptions
- type CircuitBreaker
- type CircuitBreakerCount
- func (cb CircuitBreakerCount) Allow() error
- func (cb *CircuitBreakerCount) ApplyPolicies(resp *Response)
- func (cb CircuitBreakerCount) OnStateChange(hooks ...CircuitBreakerStateChangeHook) CircuitBreakerObserver
- func (cb CircuitBreakerCount) OnTrigger(hooks ...CircuitBreakerTriggerHook) CircuitBreakerObserver
- func (cb CircuitBreakerCount) RunOnStateChangeHooks(oldState, newState CircuitBreakerState)
- func (cb CircuitBreakerCount) RunOnTriggerHooks(req *Request, err error)
- type CircuitBreakerObserver
- type CircuitBreakerPolicy
- type CircuitBreakerRatio
- func (cb CircuitBreakerRatio) Allow() error
- func (cb *CircuitBreakerRatio) ApplyPolicies(resp *Response)
- func (cb CircuitBreakerRatio) OnStateChange(hooks ...CircuitBreakerStateChangeHook) CircuitBreakerObserver
- func (cb CircuitBreakerRatio) OnTrigger(hooks ...CircuitBreakerTriggerHook) CircuitBreakerObserver
- func (cb CircuitBreakerRatio) RunOnStateChangeHooks(oldState, newState CircuitBreakerState)
- func (cb CircuitBreakerRatio) RunOnTriggerHooks(req *Request, err error)
- type CircuitBreakerState
- type CircuitBreakerStateChangeHook
- type CircuitBreakerTriggerHook
- type Client
- func New() *Client
- func NewWithClient(hc *http.Client) *Client
- func NewWithDialer(dialer *net.Dialer) *Client
- func NewWithDialerAndTransportSettings(dialer *net.Dialer, transportSettings *TransportSettings) *Client
- func NewWithLocalAddr(localAddr net.Addr) *Client
- func NewWithTransportSettings(transportSettings *TransportSettings) *Client
- func (c *Client) AddContentDecompresser(k string, d ContentDecompresser) *Client
- func (c *Client) AddContentTypeDecoder(ct string, d ContentTypeDecoder) *Client
- func (c *Client) AddContentTypeEncoder(ct string, e ContentTypeEncoder) *Client
- func (c *Client) AddRequestMiddleware(m RequestMiddleware) *Client
- func (c *Client) AddResponseMiddleware(m ResponseMiddleware) *Client
- func (c *Client) AddRetryConditions(conditions ...RetryConditionFunc) *Client
- func (c *Client) AddRetryHooks(hooks ...RetryHookFunc) *Client
- func (c *Client) AuthScheme() string
- func (c *Client) AuthToken() string
- func (c *Client) BaseURL() string
- func (c *Client) Client() *http.Client
- func (c *Client) Clone(ctx context.Context) *Client
- func (c *Client) Close() error
- func (c *Client) ContentDecompresserKeys() string
- func (c *Client) ContentDecompressers() map[string]ContentDecompresser
- func (c *Client) ContentTypeDecoders() map[string]ContentTypeDecoder
- func (c *Client) ContentTypeEncoders() map[string]ContentTypeEncoder
- func (c *Client) Context() context.Context
- func (c *Client) CookieJar() http.CookieJar
- func (c *Client) Cookies() []*http.Cookie
- func (c *Client) DebugBodyLimit() int
- func (c *Client) FormData() url.Values
- func (c *Client) HTTPTransport() (*http.Transport, error)
- func (c *Client) Header() http.Header
- func (c *Client) HeaderAuthorizationKey() string
- func (c *Client) Hedging() Hedger
- func (c *Client) IsDebug() bool
- func (c *Client) IsDisableWarn() bool
- func (c *Client) IsMethodDeleteAllowPayload() bool
- func (c *Client) IsMethodGetAllowPayload() bool
- func (c *Client) IsProxySet() bool
- func (c *Client) IsResponseSaveToFile() bool
- func (c *Client) IsRetryAllowNonIdempotent() bool
- func (c *Client) IsRetryDefaultConditions() bool
- func (c *Client) IsTrace() bool
- func (c *Client) LoadBalancer() LoadBalancer
- func (c *Client) Logger() Logger
- func (c *Client) NewRequest() *Request
- func (c *Client) OnClose(hooks ...CloseHook) *Client
- func (c *Client) OnDebugLog(dlc DebugLogCallbackFunc) *Client
- func (c *Client) OnError(hooks ...ErrorHook) *Client
- func (c *Client) OnInvalid(hooks ...ErrorHook) *Client
- func (c *Client) OnPanic(hooks ...ErrorHook) *Client
- func (c *Client) OnSuccess(hooks ...SuccessHook) *Client
- func (c *Client) PathParams() map[string]string
- func (c *Client) ProxyURL() *url.URL
- func (c *Client) QueryParams() url.Values
- func (c *Client) R() *Request
- func (c *Client) RateLimiter() RateLimiter
- func (c *Client) RemoveProxy() *Client
- func (c *Client) ResponseBodyLimit() int64
- func (c *Client) ResponseBodyUnlimitedReads() bool
- func (c *Client) ResponseSaveDirectory() string
- func (c *Client) ResultError() reflect.Type
- func (c *Client) RetryConditions() []RetryConditionFunc
- func (c *Client) RetryCount() int
- func (c *Client) RetryDelayStrategy() RetryDelayStrategyFunc
- func (c *Client) RetryHooks() []RetryHookFunc
- func (c *Client) RetryMaxWaitTime() time.Duration
- func (c *Client) RetryWaitTime() time.Duration
- func (c *Client) Scheme() string
- func (c *Client) SetAuthScheme(scheme string) *Client
- func (c *Client) SetAuthToken(token string) *Client
- func (c *Client) SetBaseURL(url string) *Client
- func (c *Client) SetBasicAuth(username, password string) *Client
- func (c *Client) SetCertificateFromFile(certFilePath, certKeyFilePath string) *Client
- func (c *Client) SetCertificateFromString(certStr, certKeyStr string) *Client
- func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
- func (c *Client) SetCircuitBreaker(cb CircuitBreaker) *Client
- func (c *Client) SetClientRootCertificateFromString(pemCerts string) *Client
- func (c *Client) SetClientRootCertificates(pemFilePaths ...string) *Client
- func (c *Client) SetClientRootCertificatesWatcher(options *CertWatcherOptions, pemFilePaths ...string) *Client
- func (c *Client) SetCloseConnection(close bool) *Client
- func (c *Client) SetContentDecompresserKeys(keys []string) *Client
- func (c *Client) SetContext(ctx context.Context) *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) SetCurlCmdDebugLog(b bool) *Client
- func (c *Client) SetCurlCmdGenerate(b bool) *Client
- func (c *Client) SetDebug(d bool) *Client
- func (c *Client) SetDebugBodyLimit(sl int) *Client
- func (c *Client) SetDebugLogFormatter(df DebugLogFormatterFunc) *Client
- func (c *Client) SetDigestAuth(username, password string) *Client
- func (c *Client) SetFormData(data map[string]string) *Client
- func (c *Client) SetHeader(header, value string) *Client
- func (c *Client) SetHeaderAny(header string, value any) *Client
- func (c *Client) SetHeaderAuthorizationKey(k string) *Client
- func (c *Client) SetHeaderVerbatim(header, value string) *Client
- func (c *Client) SetHeaderVerbatimAny(header string, value any) *Client
- func (c *Client) SetHeaders(headers map[string]string) *Client
- func (c *Client) SetHedging(h Hedger) *Client
- func (c *Client) SetJSONEscapeHTML(b bool) *Client
- func (c *Client) SetLoadBalancer(b LoadBalancer) *Client
- func (c *Client) SetLogger(l Logger) *Client
- func (c *Client) SetLoggerWarnLevel(d bool) *Client
- func (c *Client) SetMethodDeleteAllowPayload(allow bool) *Client
- func (c *Client) SetMethodGetAllowPayload(allow bool) *Client
- func (c *Client) SetPathParam(param, value string) *Client
- func (c *Client) SetPathParamAny(param string, value any) *Client
- func (c *Client) SetPathParams(params map[string]string) *Client
- func (c *Client) SetPathRawParam(param, value string) *Client
- func (c *Client) SetPathRawParamAny(param string, value any) *Client
- func (c *Client) SetPathRawParams(params map[string]string) *Client
- func (c *Client) SetProxy(proxyURL string) *Client
- func (c *Client) SetQueryParam(param, value string) *Client
- func (c *Client) SetQueryParamAny(param string, value any) *Client
- func (c *Client) SetQueryParams(params map[string]string) *Client
- func (c *Client) SetQueryParamsUnescape(unescape bool) *Client
- func (c *Client) SetRateLimiter(l RateLimiter) *Client
- func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client
- func (c *Client) SetRequestMiddlewares(middlewares ...RequestMiddleware) *Client
- func (c *Client) SetResponseBodyLimit(v int64) *Client
- func (c *Client) SetResponseBodyUnlimitedReads(b bool) *Client
- func (c *Client) SetResponseDoNotParse(notParse bool) *Client
- func (c *Client) SetResponseMiddlewares(middlewares ...ResponseMiddleware) *Client
- func (c *Client) SetResponseSaveDirectory(dirPath string) *Client
- func (c *Client) SetResponseSaveToFile(save bool) *Client
- func (c *Client) SetResultError(v any) *Client
- func (c *Client) SetRetryAllowNonIdempotent(b bool) *Client
- func (c *Client) SetRetryCount(count int) *Client
- func (c *Client) SetRetryDefaultConditions(b bool) *Client
- func (c *Client) SetRetryDelayStrategy(rs RetryDelayStrategyFunc) *Client
- func (c *Client) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Client
- func (c *Client) SetRetryWaitTime(waitTime time.Duration) *Client
- func (c *Client) SetRootCertificateFromString(pemCerts string) *Client
- func (c *Client) SetRootCertificates(pemFilePaths ...string) *Client
- func (c *Client) SetRootCertificatesWatcher(options *CertWatcherOptions, pemFilePaths ...string) *Client
- func (c *Client) SetScheme(scheme string) *Client
- func (c *Client) SetTLSClientConfig(tlsConfig *tls.Config) *Client
- func (c *Client) SetTimeout(timeout time.Duration) *Client
- func (c *Client) SetTrace(t bool) *Client
- func (c *Client) SetTransport(transport http.RoundTripper) *Client
- func (c *Client) TLSClientConfig() *tls.Config
- func (c *Client) Timeout() time.Duration
- func (c *Client) Transport() http.RoundTripper
- type CloseHook
- type ContentDecompresser
- type ContentTypeDecoder
- type ContentTypeEncoder
- type DebugLog
- type DebugLogCallbackFunc
- type DebugLogFormatterFunc
- type DebugLogRequest
- type DebugLogResponse
- type ErrorHook
- type Hedger
- type Hedging
- func (h *Hedging) Delay() time.Duration
- func (h *Hedging) IsNonReadOnlyAllowed() bool
- func (h *Hedging) MaxRequest() int
- func (h *Hedging) MaxRequestPerSecond() float64
- func (ht *Hedging) RoundTrip(req *http.Request) (*http.Response, error)
- func (h *Hedging) SetDelay(delay time.Duration) *Hedging
- func (h *Hedging) SetMaxRequest(count int) *Hedging
- func (h *Hedging) SetMaxRequestPerSecond(count float64) *Hedging
- func (h *Hedging) SetNonReadOnlyAllowed(allow bool) *Hedging
- func (h *Hedging) SetTransport(t http.RoundTripper)
- func (h *Hedging) Transport() http.RoundTripper
- type Host
- type HostState
- type HostStateChangeFunc
- type LoadBalancer
- type Logger
- type MultipartField
- type MultipartFieldCallbackFunc
- type MultipartFieldProgress
- type RateLimitSlidingWindow
- type RateLimitTokenBucket
- type RateLimiter
- type RedirectInfo
- type RedirectPolicy
- type RedirectPolicyFunc
- type Request
- func (r *Request) AddRetryConditions(conditions ...RetryConditionFunc) *Request
- func (r *Request) AddRetryHooks(hooks ...RetryHookFunc) *Request
- func (r *Request) Clone(ctx context.Context) *Request
- func (r *Request) Context() context.Context
- func (r *Request) CurlCmd() string
- func (r *Request) Delete(url string) (*Response, error)
- func (r *Request) Execute(method, url string) (res *Response, err error)
- func (r *Request) Funcs(funcs ...RequestFunc) *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) SetAuthScheme(scheme string) *Request
- func (r *Request) SetAuthToken(authToken string) *Request
- func (r *Request) SetBasicAuth(username, password string) *Request
- func (r *Request) SetBody(body any) *Request
- func (r *Request) SetCloseConnection(close bool) *Request
- func (r *Request) SetContentLength(v int64) *Request
- func (r *Request) SetContentType(ct string) *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) SetCorrelationID(id string) *Request
- func (r *Request) SetCurlCmdDebugLog(b bool) *Request
- func (r *Request) SetCurlCmdGenerate(b bool) *Request
- func (r *Request) SetDebug(d bool) *Request
- func (r *Request) SetFile(fieldName, filePath string) *Request
- func (r *Request) SetFileReader(fieldName, 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) SetHeaderAny(header string, value any) *Request
- func (r *Request) SetHeaderAuthorizationKey(k string) *Request
- func (r *Request) SetHeaderMultiValues(headers map[string][]string) *Request
- func (r *Request) SetHeaderVerbatim(header, value string) *Request
- func (r *Request) SetHeaderVerbatimAny(header string, value any) *Request
- func (r *Request) SetHeaders(headers map[string]string) *Request
- func (r *Request) SetJSONEscapeHTML(b bool) *Request
- func (r *Request) SetLabel(label string) *Request
- func (r *Request) SetLogger(l Logger) *Request
- func (r *Request) SetMethod(m string) *Request
- func (r *Request) SetMethodDeleteAllowPayload(allow bool) *Request
- func (r *Request) SetMethodGetAllowPayload(allow bool) *Request
- func (r *Request) SetMultipartBoundary(boundary string) *Request
- func (r *Request) SetMultipartField(fieldName, fileName, contentType string, reader io.Reader) *Request
- func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request
- func (r *Request) SetMultipartFormData(data map[string]string) *Request
- func (r *Request) SetMultipartOrderedFormData(name string, values []string) *Request
- func (r *Request) SetPathParam(param, value string) *Request
- func (r *Request) SetPathParamAny(param string, value any) *Request
- func (r *Request) SetPathParams(params map[string]string) *Request
- func (r *Request) SetPathRawParam(param, value string) *Request
- func (r *Request) SetPathRawParamAny(param string, value any) *Request
- func (r *Request) SetPathRawParams(params map[string]string) *Request
- func (r *Request) SetQueryParam(param, value string) *Request
- func (r *Request) SetQueryParamAny(param string, value any) *Request
- func (r *Request) SetQueryParams(params map[string]string) *Request
- func (r *Request) SetQueryParamsFromValues(params url.Values) *Request
- func (r *Request) SetQueryParamsUnescape(unescape bool) *Request
- func (r *Request) SetQueryString(query string) *Request
- func (r *Request) SetResponseBodyLimit(v int64) *Request
- func (r *Request) SetResponseBodyUnlimitedReads(b bool) *Request
- func (r *Request) SetResponseDoNotParse(notParse bool) *Request
- func (r *Request) SetResponseExpectContentType(contentType string) *Request
- func (r *Request) SetResponseForceContentType(contentType string) *Request
- func (r *Request) SetResponseSaveFileName(file string) *Request
- func (r *Request) SetResponseSaveToFile(save bool) *Request
- func (r *Request) SetResult(v any) *Request
- func (r *Request) SetResultError(err any) *Request
- func (r *Request) SetRetryAllowNonIdempotent(b bool) *Request
- func (r *Request) SetRetryConditions(conditions ...RetryConditionFunc) *Request
- func (r *Request) SetRetryCount(count int) *Request
- func (r *Request) SetRetryDefaultConditions(b bool) *Request
- func (r *Request) SetRetryDelayStrategy(rs RetryDelayStrategyFunc) *Request
- func (r *Request) SetRetryHooks(hooks ...RetryHookFunc) *Request
- func (r *Request) SetRetryMaxWaitTime(maxWaitTime time.Duration) *Request
- func (r *Request) SetRetryWaitTime(waitTime time.Duration) *Request
- func (r *Request) SetTimeout(timeout time.Duration) *Request
- func (r *Request) SetTrace(t bool) *Request
- func (r *Request) SetURL(url string) *Request
- func (r *Request) Trace(url string) (*Response, error)
- func (r *Request) TraceInfo() TraceInfo
- func (r *Request) WithContext(ctx context.Context) *Request
- type RequestFeedback
- type RequestFunc
- type RequestMiddleware
- type Response
- func (r *Response) Bytes() []byte
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Duration() time.Duration
- func (r *Response) Header() http.Header
- func (r *Response) IsStatusFailure() bool
- func (r *Response) IsStatusSuccess() bool
- func (r *Response) Proto() string
- func (r *Response) ReceivedAt() time.Time
- func (r *Response) RedirectHistory() []*RedirectInfo
- func (r *Response) Result() any
- func (r *Response) ResultError() any
- func (r *Response) Size() int64
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- func (r *Response) String() string
- type ResponseError
- type ResponseMiddleware
- type RetryConditionFunc
- type RetryDelayStrategyFunc
- type RetryHookFunc
- type RoundRobin
- type SRVWeightedRoundRobin
- func (swrr *SRVWeightedRoundRobin) Close() error
- func (swrr *SRVWeightedRoundRobin) Feedback(f *RequestFeedback)
- func (swrr *SRVWeightedRoundRobin) NextWithContext(ctx context.Context) (string, error)
- func (swrr *SRVWeightedRoundRobin) Refresh() error
- func (swrr *SRVWeightedRoundRobin) SetOnStateChange(fn HostStateChangeFunc)
- func (swrr *SRVWeightedRoundRobin) SetRecoveryDuration(d time.Duration)
- func (swrr *SRVWeightedRoundRobin) SetRefreshDuration(d time.Duration)
- type SSE
- type SSEErrorFunc
- type SSEMessageFunc
- type SSEOpenFunc
- type SSERequestFailureFunc
- type SSESource
- func (sse *SSESource) AddEventListener(eventName string, ef SSEMessageFunc, result any) *SSESource
- func (sse *SSESource) AddHeader(header, value string) *SSESource
- func (sse *SSESource) Close()
- func (sse *SSESource) Context() context.Context
- func (sse *SSESource) Get() error
- func (sse *SSESource) Logger() Logger
- func (sse *SSESource) OnError(ef SSEErrorFunc) *SSESource
- func (sse *SSESource) OnMessage(ef SSEMessageFunc, result any) *SSESource
- func (sse *SSESource) OnOpen(ef SSEOpenFunc) *SSESource
- func (sse *SSESource) OnRequestFailure(ef SSERequestFailureFunc) *SSESource
- func (sse *SSESource) SetBody(body io.Reader) *SSESource
- func (sse *SSESource) SetContext(ctx context.Context) *SSESource
- func (sse *SSESource) SetHeader(header, value string) *SSESource
- func (sse *SSESource) SetLogger(l Logger) *SSESource
- func (sse *SSESource) SetMethod(method string) *SSESource
- func (sse *SSESource) SetRetryCount(count int) *SSESource
- func (sse *SSESource) SetRetryMaxWaitTime(maxWaitTime time.Duration) *SSESource
- func (sse *SSESource) SetRetryWaitTime(waitTime time.Duration) *SSESource
- func (sse *SSESource) SetSizeMaxBuffer(bufSize int) *SSESource
- func (sse *SSESource) SetTLSClientConfig(tlsConfig *tls.Config) *SSESource
- func (sse *SSESource) SetTransport(transport http.RoundTripper) *SSESource
- func (sse *SSESource) SetURL(url string) *SSESource
- func (sse *SSESource) TLSClientConfig() *tls.Config
- type SuccessHook
- type TLSClientConfiger
- type TraceInfo
- type TransportSettings
- type WeightedRoundRobin
- func (wrr *WeightedRoundRobin) Close() error
- func (wrr *WeightedRoundRobin) Feedback(f *RequestFeedback)
- func (wrr *WeightedRoundRobin) NextWithContext(ctx context.Context) (string, error)
- func (wrr *WeightedRoundRobin) Refresh(hosts ...*Host) error
- func (wrr *WeightedRoundRobin) SetOnStateChange(fn HostStateChangeFunc)
- func (wrr *WeightedRoundRobin) SetRecoveryDuration(d time.Duration)
Constants ¶
const ( // MethodGet is the HTTP GET method. MethodGet = "GET" // MethodPost is the HTTP POST method. MethodPost = "POST" // MethodPut is the HTTP PUT method. MethodPut = "PUT" // MethodDelete is the HTTP DELETE method. MethodDelete = "DELETE" // MethodPatch is the HTTP PATCH method. MethodPatch = "PATCH" // MethodHead is the HTTP HEAD method. MethodHead = "HEAD" // MethodOptions is the HTTP OPTIONS method. MethodOptions = "OPTIONS" // MethodTrace is the HTTP TRACE method. MethodTrace = "TRACE" )
const Version = "3.0.0-rc.3"
Version is the current Resty library version string.
Variables ¶
var ( // ErrNotHttpTransportType is returned when the underlying transport is not an [http.Transport]. ErrNotHttpTransportType = errors.New("resty: not a http.Transport type") // ErrUnsupportedRequestBodyKind is returned when the request body is of an unsupported kind. ErrUnsupportedRequestBodyKind = errors.New("resty: unsupported request body kind") // ErrReaderNotSeekable is returned when a non-seekable request body reader is // used on a retry attempt. This applies to both generic [io.Reader] request // bodies (see [Request.SetBody]) and to [MultipartField.Reader] when retrying. ErrReaderNotSeekable = errors.New("resty: reader is not seekable on request retry") )
var ( // ErrDigestBadChallenge is returned when the server sends a malformed or // unrecognisable Digest challenge in the WWW-Authenticate header. ErrDigestBadChallenge = errors.New("resty: digest: challenge is bad") // ErrDigestInvalidCharset is returned when the Digest challenge specifies // a charset other than UTF-8. ErrDigestInvalidCharset = errors.New("resty: digest: invalid charset") // ErrDigestAlgNotSupported is returned when the Digest challenge uses a // hash algorithm not supported by Resty (see [RFC 7616 Section 6.1]). // // [RFC 7616 Section 6.1]: https://datatracker.ietf.org/doc/html/rfc7616#section-6.1 ErrDigestAlgNotSupported = errors.New("resty: digest: algorithm is not supported") // ErrDigestQopNotSupported is returned when none of the quality-of-protection // (qop) directives in the Digest challenge are supported by Resty. // Resty supports auth and auth-int. ErrDigestQopNotSupported = errors.New("resty: digest: qop is not supported") )
var ( // InMemoryJSONMarshal function performs the JSON marshalling completely in memory. // // c := resty.New() // defer c.Close() // // c.AddContentTypeEncoder("application/json", resty.InMemoryJSONMarshal) InMemoryJSONMarshal = func(w io.Writer, v any) error { jsonData, err := json.Marshal(v) if err != nil { return err } _, err = w.Write(jsonData) return err } // InMemoryJSONUnmarshal function performs the JSON unmarshalling completely in memory. // // c := resty.New() // defer c.Close() // // c.AddContentTypeDecoder("application/json", resty.InMemoryJSONUnmarshal) InMemoryJSONUnmarshal = func(r io.Reader, v any) error { byteData, err := io.ReadAll(r) if err != nil { return err } return json.Unmarshal(byteData, v) } // InMemoryXMLMarshal function performs the XML marshalling completely in memory. // // c := resty.New() // defer c.Close() // // c.AddContentTypeEncoder("application/xml", resty.InMemoryXMLMarshal) InMemoryXMLMarshal = func(w io.Writer, v any) error { xmlData, err := xml.Marshal(v) if err != nil { return err } _, err = w.Write(xmlData) return err } // InMemoryXMLUnmarshal function performs the XML unmarshalling completely in memory. // // c := resty.New() // defer c.Close() // // c.AddContentTypeDecoder("application/xml", resty.InMemoryXMLUnmarshal) InMemoryXMLUnmarshal = func(r io.Reader, v any) error { byteData, err := io.ReadAll(r) if err != nil { return err } return xml.Unmarshal(byteData, v) } )
var ErrCircuitBreakerOpen = errors.New("resty: circuit breaker open")
ErrCircuitBreakerOpen is returned by Client execute method when the circuit breaker is in the open state and a request is blocked.
var ( // ErrContentDecompresserNotFound is returned when no decompresser is registered // for the Content-Encoding directive present in the response. ErrContentDecompresserNotFound = errors.New("resty: content decoder not found") )
var ErrNoActiveHost = errors.New("resty: no active host")
ErrNoActiveHost is returned when all hosts are inactive in the load balancer.
var ErrNoBaseURLs = errors.New("resty: no base URLs found")
ErrNoBaseURLs is returned when no base URLs are found.
var ErrRateLimitExceeded = errors.New("resty: rate limit exceeded")
ErrRateLimitExceeded is returned by Client execute method when the rate limiter rejects a request. This occurs when the context is cancelled or the deadline expires before a token becomes available, or immediately if the rate limiter implementation rejects the request for any other reason.
var ErrReadExceedsThresholdLimit = errors.New("resty: read exceeds the threshold limit")
ErrReadExceedsThresholdLimit is returned when the response body read exceeds the limit set by Client.SetResponseBodyLimit or Request.SetResponseBodyLimit.
Functions ¶
func CircuitBreaker5xxPolicy ¶
CircuitBreaker5xxPolicy is the default CircuitBreakerPolicy. It classifies a response as a failure when the HTTP status code is greater than or equal to 500.
func DebugLogFormatter ¶
DebugLogFormatter formats a DebugLog as a human-readable multi-line string.
This is the default debug log formatter used by Resty.
func DebugLogJSONFormatter ¶
DebugLogJSONFormatter formats a DebugLog as a JSON string.
func MiddlewareRequestCreate ¶
MiddlewareRequestCreate prepares the HTTP request from the user-provided Request values. It performs the following operations:
- Parse the request URL with path params and query params
- Parse the request headers from client and request level
- Parse the request body based on the content type and body type
- Create the underlying http.Request object
- Add credentials such as Basic Auth and Token Auth into the request
Returns an error if request preparation fails.
func MiddlewareResponseAutoParse ¶
MiddlewareResponseAutoParse parses the response body automatically using the Content-Type decoder registered via Client.AddContentTypeDecoder. When Request.SetResult, Request.SetResultError, or Client.SetResultError is used, the body is automatically unmarshalled into the provided object.
func MiddlewareResponseSaveToFile ¶
MiddlewareResponseSaveToFile writes the HTTP response body to a file. The filename is determined in the following order:
- Request.SetResponseSaveFileName
- Content-Disposition header
- Request URL path using path.Base
- Request URL hostname if the path is empty or "/"
Content-Disposition filename values are sanitized before use. Absolute paths and parent-directory traversal segments are rejected.
If Client.SetResponseSaveDirectory is set and Request.SetResponseSaveFileName provides a relative path, the final path must remain within the configured response save directory after cleaning, otherwise this middleware returns an error.
func RetryConditionStatus5XX ¶
RetryConditionStatus5XX is a RetryConditionFunc that returns true when the response status code is 500 or above, excluding 501 (Not Implemented).
- 5XX status codes are generally considered temporary server errors that may be resolved on retry.
- The rationale for excluding 501 Not Implemented is that it indicates the server does not support the functionality required to fulfill the request.
func RetryConditionStatusTooManyRequests ¶
RetryConditionStatusTooManyRequests is a RetryConditionFunc that returns true if the response status code is 429 Too Many Requests.
- The 429 status code indicates that the user has sent too many requests in a given amount of time ("rate limiting").
- Retrying after receiving a 429 status code can be effective, especially if the server includes a Retry-After header indicating when to retry.
func RetryConditionStatusZero ¶
RetryConditionStatusZero is a RetryConditionFunc that returns true if the response status code is 0.
- A status code of 0 typically indicates that no response was received from the server, which can occur due to network errors, timeouts, or other issues that prevent the request from being completed.
- Retrying when a status code of 0 is encountered can be effective, as it may allow the request to succeed on subsequent attempts if the underlying issue is transient.
Types ¶
type CertWatcherOptions ¶
type CertWatcherOptions struct {
// PoolInterval is the frequency at which resty will check if the PEM file needs to be reloaded.
// Default is 24 hours.
PoolInterval time.Duration
}
CertWatcherOptions configures the certificate file watcher that reloads TLS certificates dynamically. See Client.SetRootCertificatesWatcher, Client.SetClientRootCertificatesWatcher.
type CircuitBreaker ¶
type CircuitBreaker interface {
// Allow checks if a request is allowed to proceed based on the current state of the circuit breaker.
// It returns [ErrCircuitBreakerOpen] when the breaker is open or when a half-open
// probe request is already in flight.
Allow() error
// ApplyPolicies inspects the given HTTP response against the registered policies to determine
// if it should be classified as a failure. It updates the sliding window counts and
// manages state transitions accordingly.
ApplyPolicies(*Response)
}
CircuitBreaker is an interface for implementing a circuit breaker pattern to protect downstream services from cascading failures. It provides methods to check if a request is allowed and apply policies to classify responses as failures.
type CircuitBreakerCount ¶
type CircuitBreakerCount struct {
// contains filtered or unexported fields
}
CircuitBreakerCount implements a count-based circuit breaker. It trips when the absolute number of request failures within the sliding window reaches the configured failureThreshold. Once open, it recovers after resetTimeout and closes again when successThreshold consecutive probe successes are observed.
Create via NewCircuitBreakerCount and register via Client.SetCircuitBreaker.
func NewCircuitBreakerCount ¶
func NewCircuitBreakerCount(failureThreshold uint64, successThreshold uint64, resetTimeout time.Duration, policies ...CircuitBreakerPolicy) *CircuitBreakerCount
NewCircuitBreakerCount creates a circuit breaker that trips when the absolute number of request failures within the sliding window reaches failureThreshold. Once open, it recovers after resetTimeout and closes again when successThreshold consecutive probe successes are observed.
The optional policies override the detection logic used to classify a response as a failure. When no policies are provided, CircuitBreaker5xxPolicy is used by default.
func (CircuitBreakerCount) Allow ¶
func (cb CircuitBreakerCount) Allow() error
Allow checks if a request is allowed to proceed based on the current state of the circuit breaker.
func (*CircuitBreakerCount) ApplyPolicies ¶
func (cb *CircuitBreakerCount) ApplyPolicies(resp *Response)
ApplyPolicies inspects the given HTTP response against the registered policies to determine if it should be classified as a failure. It updates the sliding window counts and manages state transitions accordingly.
func (CircuitBreakerCount) OnStateChange ¶
func (cb CircuitBreakerCount) OnStateChange(hooks ...CircuitBreakerStateChangeHook) CircuitBreakerObserver
OnStateChange registers one or more CircuitBreakerStateChangeHook functions that are invoked whenever the circuit breaker transitions between states.
func (CircuitBreakerCount) OnTrigger ¶
func (cb CircuitBreakerCount) OnTrigger(hooks ...CircuitBreakerTriggerHook) CircuitBreakerObserver
OnTrigger registers one or more CircuitBreakerTriggerHook functions that are invoked each time the circuit breaker rejects a request in the open state.
func (CircuitBreakerCount) RunOnStateChangeHooks ¶
func (cb CircuitBreakerCount) RunOnStateChangeHooks(oldState, newState CircuitBreakerState)
RunOnStateChangeHooks method executes all registered state change hooks with the given old and new states.
func (CircuitBreakerCount) RunOnTriggerHooks ¶
RunOnTriggerHooks method executes all registered trigger hooks with the given request and error.
type CircuitBreakerObserver ¶
type CircuitBreakerObserver interface {
// OnTrigger registers one or more [CircuitBreakerTriggerHook] functions that are invoked
// each time the circuit breaker rejects a request in the open state.
OnTrigger(...CircuitBreakerTriggerHook) CircuitBreakerObserver
// RunOnTriggerHooks executes all registered trigger hooks with the given request and error.
RunOnTriggerHooks(*Request, error)
// OnStateChange registers one or more [CircuitBreakerStateChangeHook] functions that are
// invoked whenever the circuit breaker transitions between states.
OnStateChange(...CircuitBreakerStateChangeHook) CircuitBreakerObserver
// RunOnStateChangeHooks executes all registered state change hooks with the given old and new states.
RunOnStateChangeHooks(oldState, newState CircuitBreakerState)
}
CircuitBreakerObserver is an interface for observing circuit breaker events via hooks. It provides methods to register hooks for trigger and state change events, and to execute those hooks.
type CircuitBreakerPolicy ¶
CircuitBreakerPolicy is a function that inspects a Response and returns true when that response should be counted as a failure and potentially trip the circuit breaker. Multiple policies can be registered; the breaker trips if any policy returns true.
type CircuitBreakerRatio ¶
type CircuitBreakerRatio struct {
// contains filtered or unexported fields
}
CircuitBreakerRatio implements a ratio-based circuit breaker. It trips when the ratio of failures to total requests within the sliding window reaches the configured failureRatio, provided at least minRequests have been observed. Once open, it recovers after resetTimeout. The half-open probe closes the breaker after one successful request.
Create via NewCircuitBreakerRatio and register via Client.SetCircuitBreaker.
func NewCircuitBreakerRatio ¶
func NewCircuitBreakerRatio(failureRatio float64, minRequests uint64, resetTimeout time.Duration, policies ...CircuitBreakerPolicy) *CircuitBreakerRatio
NewCircuitBreakerRatio creates a circuit breaker that trips when the ratio of failures to total requests within the sliding window reaches failureRatio (0.0–1.0), provided at least minRequests have been observed. Once open, it recovers after resetTimeout. The half-open probe closes the breaker after one successful request.
The optional policies override the detection logic used to classify a response as a failure. When no policies are provided, CircuitBreaker5xxPolicy is used by default.
func (CircuitBreakerRatio) Allow ¶
func (cb CircuitBreakerRatio) Allow() error
Allow checks if a request is allowed to proceed based on the current state of the circuit breaker.
func (*CircuitBreakerRatio) ApplyPolicies ¶
func (cb *CircuitBreakerRatio) ApplyPolicies(resp *Response)
ApplyPolicies inspects the given HTTP response against the registered policies to determine if it should be classified as a failure. It updates the sliding window counts and manages state transitions accordingly.
func (CircuitBreakerRatio) OnStateChange ¶
func (cb CircuitBreakerRatio) OnStateChange(hooks ...CircuitBreakerStateChangeHook) CircuitBreakerObserver
OnStateChange registers one or more CircuitBreakerStateChangeHook functions that are invoked whenever the circuit breaker transitions between states.
func (CircuitBreakerRatio) OnTrigger ¶
func (cb CircuitBreakerRatio) OnTrigger(hooks ...CircuitBreakerTriggerHook) CircuitBreakerObserver
OnTrigger registers one or more CircuitBreakerTriggerHook functions that are invoked each time the circuit breaker rejects a request in the open state.
func (CircuitBreakerRatio) RunOnStateChangeHooks ¶
func (cb CircuitBreakerRatio) RunOnStateChangeHooks(oldState, newState CircuitBreakerState)
RunOnStateChangeHooks method executes all registered state change hooks with the given old and new states.
func (CircuitBreakerRatio) RunOnTriggerHooks ¶
RunOnTriggerHooks method executes all registered trigger hooks with the given request and error.
type CircuitBreakerState ¶
type CircuitBreakerState uint32
CircuitBreakerState is the type for the three circuit breaker states: CircuitBreakerStateClosed, CircuitBreakerStateOpen, and CircuitBreakerStateHalfOpen.
const ( // CircuitBreakerStateClosed is the normal operating state: all requests are // forwarded and failures are tracked against the configured threshold. CircuitBreakerStateClosed CircuitBreakerState = iota // CircuitBreakerStateOpen is the tripped state: all requests are blocked and // return [ErrCircuitBreakerOpen] immediately. After the reset timeout the // breaker transitions to [CircuitBreakerStateHalfOpen]. CircuitBreakerStateOpen // CircuitBreakerStateHalfOpen is the recovery probe state: a single request // is allowed through. A success transitions to [CircuitBreakerStateClosed]; // a failure transitions back to [CircuitBreakerStateOpen]. CircuitBreakerStateHalfOpen )
type CircuitBreakerStateChangeHook ¶
type CircuitBreakerStateChangeHook func(oldState, newState CircuitBreakerState)
CircuitBreakerStateChangeHook is called whenever the circuit breaker transitions between states (Closed → Open, Open → Half-Open, Half-Open → Closed, etc.). It receives the previous and the new CircuitBreakerState.
type CircuitBreakerTriggerHook ¶
CircuitBreakerTriggerHook is called each time the circuit breaker blocks a request because it is in the open state. The hook receives the blocked Request and ErrCircuitBreakerOpen as the error.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client struct is used to create a Resty client with client-level settings, these settings apply to all the requests raised from the client.
Resty also provides an option to override most of the client settings at Request level.
func NewWithClient ¶
NewWithClient creates a new Resty client with the given http.Client.
func NewWithDialer ¶
NewWithDialer creates a new Resty client with the given net.Dialer.
func NewWithDialerAndTransportSettings ¶
func NewWithDialerAndTransportSettings(dialer *net.Dialer, transportSettings *TransportSettings) *Client
NewWithDialerAndTransportSettings creates a new Resty client with the given net.Dialer and TransportSettings.
func NewWithLocalAddr ¶
NewWithLocalAddr creates a new Resty client with the given local address.
func NewWithTransportSettings ¶
func NewWithTransportSettings(transportSettings *TransportSettings) *Client
NewWithTransportSettings creates a new Resty client with the provided TransportSettings.
func (*Client) AddContentDecompresser ¶
func (c *Client) AddContentDecompresser(k string, d ContentDecompresser) *Client
AddContentDecompresser method adds a Content-Encoding (RFC 9110) decompresser and its directive to the client.
NOTE: It overwrites the Decompresser function if the given Content-Encoding directive already exists.
func (*Client) AddContentTypeDecoder ¶
func (c *Client) AddContentTypeDecoder(ct string, d ContentTypeDecoder) *Client
AddContentTypeDecoder method adds a Content-Type decoder to the client.
NOTE: It overwrites the decoder function if the given Content-Type key already exists.
func (*Client) AddContentTypeEncoder ¶
func (c *Client) AddContentTypeEncoder(ct string, e ContentTypeEncoder) *Client
AddContentTypeEncoder method adds a Content-Type encoder to the client.
NOTE: It overwrites the encoder function if the given Content-Type key already exists.
func (*Client) AddRequestMiddleware ¶
func (c *Client) AddRequestMiddleware(m RequestMiddleware) *Client
AddRequestMiddleware method appends a request middleware to the request chain. Method accepts a function of type RequestMiddleware. All the request middlewares are applied; before sending the request to the server.
It is ideal for:
- Intercept Request instance for manipulation
- Terminate the Request early by returning non-nil error
- etc.
See methods Client.SetRequestMiddlewares.
client.AddRequestMiddleware(func(c *resty.Client, r *resty.Request) error {
// Now you have access to the Client and Request instance
// manipulate it as per your need
return nil // if it’s successful otherwise return error
})
Resty provides some built-in request middlewares such as:
- [PrepareRequestMiddleware]: creates the http.Request instance using the Resty Request instance.
func (*Client) AddResponseMiddleware ¶
func (c *Client) AddResponseMiddleware(m ResponseMiddleware) *Client
AddResponseMiddleware method appends a response middleware to the after-response chain. All the response middlewares are executed with a Response instance before returning the response to the caller.
NOTE:
- In v3, all response middleware is executed irrespective of the error. The error details are passed down to the subsequent response middleware through the Response.CascadeError field.
- Before processing your middleware, ensure to check Response.CascadeError.
Method accepts a function of type ResponseMiddleware.
client.AddResponseMiddleware(func(c *resty.Client, r *resty.Response) error {
// Now you have access to the Client and Response instance
// Also, you could access request via Response.Request i.e., r.Request
// manipulate it as per your need
return nil // if it’s successful otherwise return error
})
func (*Client) AddRetryConditions ¶
func (c *Client) AddRetryConditions(conditions ...RetryConditionFunc) *Client
AddRetryConditions method adds one or more retry condition functions to the client. These retry conditions are executed to determine if the request can be retried. The request will retry if any functions return `true`, otherwise return `false`.
NOTE:
- Retry conditions are executed on each retry attempt.
- Default retry conditions are executed first.
- Client-level retry conditions are applied to all requests.
- Request-level retry conditions are executed before client-level retry conditions. See Request.AddRetryConditions, Request.SetRetryConditions
- Once a retry condition returns true, the remaining retry conditions are not executed.
- Retry conditions are executed in the order in which they are added.
func (*Client) AddRetryHooks ¶
func (c *Client) AddRetryHooks(hooks ...RetryHookFunc) *Client
AddRetryHooks method appends one or more retry hook functions to the client; each hook is called on every retry attempt.
NOTE:
- Retry hooks are executed on each retry attempt.
- The request-level retry hooks are executed first before client-level hooks. See Request.AddRetryHooks, Request.SetRetryHooks
- Retry hooks are executed in the order in which they are added.
func (*Client) AuthScheme ¶
AuthScheme method returns the auth scheme name set in the client instance.
func (*Client) AuthToken ¶
AuthToken method returns the auth token value registered in the client instance.
func (*Client) Client ¶
Client method returns the underlying http.Client.
func (*Client) Clone ¶
Clone method returns a clone of the original client.
NOTE: Use with care:
- Interface values are not deeply cloned. Thus, both the original and the clone will use the same value.
- It is not safe for concurrent use. You should only use this method when you are sure that any other concurrent process is not using the client or client instance is protected by a mutex.
func (*Client) Close ¶
Close method executes all registered CloseHook callbacks and releases client resources. It is safe to call Close multiple times; subsequent calls are no-op.
func (*Client) ContentDecompresserKeys ¶
ContentDecompresserKeys method returns all the registered content-encoding Decompressers keys as comma-separated string.
func (*Client) ContentDecompressers ¶
func (c *Client) ContentDecompressers() map[string]ContentDecompresser
ContentDecompressers method returns all the registered content-encoding Decompressers.
func (*Client) ContentTypeDecoders ¶
func (c *Client) ContentTypeDecoders() map[string]ContentTypeDecoder
ContentTypeDecoders method returns all the registered content type decoders.
func (*Client) ContentTypeEncoders ¶
func (c *Client) ContentTypeEncoders() map[string]ContentTypeEncoder
ContentTypeEncoders method returns all the registered content type encoders.
func (*Client) Context ¶
Context method returns the context.Context from the client instance.
func (*Client) CookieJar ¶
CookieJar method returns the HTTP cookie jar instance from the underlying Go HTTP Client.
func (*Client) DebugBodyLimit ¶
DebugBodyLimit method returns the debug body size limit set on the client.
func (*Client) FormData ¶
FormData method returns the form parameters and their values from the client instance.
func (*Client) HTTPTransport ¶
HTTPTransport method returns the underlying http.Transport, or ErrNotHttpTransportType if the transport is not of that type.
func (*Client) HeaderAuthorizationKey ¶
HeaderAuthorizationKey method returns the HTTP header name for Authorization from the client instance.
func (*Client) Hedging ¶
Hedging method returns the Hedger implementation set on the client, or nil if hedging is disabled.
func (*Client) IsDebug ¶
IsDebug method returns `true` if the client is in debug mode; otherwise, it is `false`.
func (*Client) IsDisableWarn ¶
IsDisableWarn method returns `true` if the warning message is disabled; otherwise, it is `false`.
func (*Client) IsMethodDeleteAllowPayload ¶
IsMethodDeleteAllowPayload method returns true if the DELETE method is allowed to carry a payload; otherwise false.
More info, refer to GH#881
func (*Client) IsMethodGetAllowPayload ¶
IsMethodGetAllowPayload method returns true if the GET method is allowed to carry a payload; otherwise false.
func (*Client) IsProxySet ¶
IsProxySet method returns true if a proxy URL has been explicitly set on the client; otherwise false. By default, the proxy is determined from the environment; see http.ProxyFromEnvironment.
func (*Client) IsResponseSaveToFile ¶
IsResponseSaveToFile method returns true if saving responses to file is enabled; otherwise false.
func (*Client) IsRetryAllowNonIdempotent ¶
IsRetryAllowNonIdempotent method reports whether retry is allowed for non-idempotent HTTP methods. The default is false.
func (*Client) IsRetryDefaultConditions ¶
IsRetryDefaultConditions method reports whether the default retry conditions are enabled.
The default is true.
func (*Client) IsTrace ¶
IsTrace method returns true if the trace is enabled on the client instance; otherwise, it returns false.
func (*Client) LoadBalancer ¶
func (c *Client) LoadBalancer() LoadBalancer
LoadBalancer method returns the load balancer set on the client, or nil if none is set.
func (*Client) NewRequest ¶
NewRequest method is an alias for Client.R.
func (*Client) OnClose ¶
OnClose method adds a callback that will be run whenever the client is closed. The hooks are executed in the order they were registered.
func (*Client) OnDebugLog ¶
func (c *Client) OnDebugLog(dlc DebugLogCallbackFunc) *Client
OnDebugLog method sets the debug-log callback on the client instance. The registered callback is invoked before Resty logs each debug entry.
func (*Client) OnError ¶
OnError method adds a callback that will be run whenever a request execution fails. This is called after all retries have been attempted (if any). If there was a response from the server, the error will be wrapped in ResponseError which has the last response received from the server.
client.OnError(func(req *resty.Request, err error) {
if v, ok := err.(*resty.ResponseError); ok {
// Do something with v.Response
}
// Log the error, increment a metric, etc...
})
Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.
NOTE:
- Do not use Client setter methods within OnError hooks; deadlock will happen.
func (*Client) OnInvalid ¶
OnInvalid method adds a callback that will be run whenever a request execution fails before it starts because the request is invalid.
Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.
NOTE:
- Do not use Client setter methods within OnInvalid hooks; deadlock will happen.
func (*Client) OnPanic ¶
OnPanic method adds a callback that will be run whenever a request execution panics.
Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.
If an Client.OnSuccess, Client.OnError, or Client.OnInvalid callback panics, then exactly one rule can be violated.
NOTE:
- Do not use Client setter methods within OnPanic hooks; deadlock will happen.
func (*Client) OnSuccess ¶
func (c *Client) OnSuccess(hooks ...SuccessHook) *Client
OnSuccess method adds a callback that will be run whenever a request execution succeeds. This is called after all retries have been attempted (if any).
Out of the Client.OnSuccess, Client.OnError, Client.OnInvalid, Client.OnPanic callbacks, exactly one set will be invoked for each call to Request.Execute that completes.
NOTE:
- Do not use Client setter methods within OnSuccess hooks; deadlock will happen.
func (*Client) PathParams ¶
PathParams method returns the path parameters set on the client.
func (*Client) QueryParams ¶
QueryParams method returns all query parameters and their values from the client instance.
func (*Client) R ¶
R method creates and returns a new Request instance for building and executing HTTP requests.
func (*Client) RateLimiter ¶
func (c *Client) RateLimiter() RateLimiter
RateLimiter method returns the RateLimiter configured on the client, or nil if none is set.
func (*Client) RemoveProxy ¶
RemoveProxy method removes the proxy configuration from the Resty client
client.RemoveProxy()
func (*Client) ResponseBodyLimit ¶
ResponseBodyLimit method returns the value max body size limit in bytes from the client instance.
func (*Client) ResponseBodyUnlimitedReads ¶
ResponseBodyUnlimitedReads method returns true if enabled. Otherwise, it returns false
func (*Client) ResponseSaveDirectory ¶
ResponseSaveDirectory method returns the output directory value from the client.
func (*Client) ResultError ¶
ResultError method returns the common error type registered on the client, or nil if none is set.
func (*Client) RetryConditions ¶
func (c *Client) RetryConditions() []RetryConditionFunc
RetryConditions method returns all the retry condition functions.
func (*Client) RetryCount ¶
RetryCount method returns the retry count value from the client instance.
func (*Client) RetryDelayStrategy ¶
func (c *Client) RetryDelayStrategy() RetryDelayStrategyFunc
RetryDelayStrategy method returns the custom retry delay strategy function, or nil if none is set.
func (*Client) RetryHooks ¶
func (c *Client) RetryHooks() []RetryHookFunc
RetryHooks method returns all the retry hook functions.
func (*Client) RetryMaxWaitTime ¶
RetryMaxWaitTime method returns the maximum wait time between retry attempts.
func (*Client) RetryWaitTime ¶
RetryWaitTime method returns the minimum wait time between retry attempts.
func (*Client) SetAuthScheme ¶
SetAuthScheme method sets the auth scheme type in the HTTP request. For Example:
Authorization: <auth-scheme-value> <auth-token-value>
For Example: To set the scheme to use OAuth
client.SetAuthScheme("OAuth")
This auth scheme gets added to all the requests raised from this client instance. Also, it can be overridden at the request level.
Information about auth schemes can be found in RFC 7235, IANA HTTP Auth schemes.
func (*Client) SetAuthToken ¶
SetAuthToken method sets the auth token of the Authorization header for all HTTP requests. The default auth scheme is Bearer; it can be customized via Client.SetAuthScheme.
Authorization: <auth-scheme> <auth-token-value>
For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
client.SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
This auth token gets added to all the requests raised from this client instance. Also, it can be overridden at the request level.
See Request.SetAuthToken.
func (*Client) SetBaseURL ¶
SetBaseURL method sets the Base URL in the client instance. It will be used with a request raised from this client with a relative URL
// Setting HTTP address
client.SetBaseURL("http://myjeeva.com")
// Setting HTTPS address
client.SetBaseURL("https://myjeeva.com")
func (*Client) SetBasicAuth ¶
SetBasicAuth method sets the basic authentication header in the HTTP request.
Authorization: Basic <base64-encoded-value>
For example: To set the header for username "go-resty" and password "welcome"
client.SetBasicAuth("go-resty", "welcome")
This basic auth information is added to all requests from this client instance. It can also be overridden at the request level.
See Request.SetBasicAuth.
func (*Client) SetCertificateFromFile ¶
SetCertificateFromFile method sets client certificates into Resty from cert and key files to perform SSL client authentication.
client.SetCertificateFromFile("certs/client.pem", "certs/client.key")
func (*Client) SetCertificateFromString ¶
SetCertificateFromString method sets client certificates into Resty from strings to perform SSL client authentication.
myClientCertStr := `-----BEGIN CERTIFICATE----- ... cert content ... -----END CERTIFICATE-----` myClientCertKeyStr := `-----BEGIN PRIVATE KEY----- ... cert key content ... -----END PRIVATE KEY-----` client.SetCertificateFromString(myClientCertStr, myClientCertKeyStr)
func (*Client) SetCertificates ¶
func (c *Client) SetCertificates(certs ...tls.Certificate) *Client
SetCertificates method sets one or more client certificates into Resty for SSL client authentication.
cert, err := tls.LoadX509KeyPair("certs/client.pem", "certs/client.key")
if err != nil {
log.Printf("ERROR client certificate/key parsing error: %v", err)
return
}
client.SetCertificates(cert)
func (*Client) SetCircuitBreaker ¶
func (c *Client) SetCircuitBreaker(cb CircuitBreaker) *Client
SetCircuitBreaker method sets the CircuitBreaker on the client to prevent sending requests that are likely to fail.
For example, to use a count-based circuit breaker:
client.SetCircuitBreaker(NewCircuitBreakerCount(5, 1, 30*time.Second))
func (*Client) SetClientRootCertificateFromString ¶
SetClientRootCertificateFromString method helps to add a client root certificate from the string into the Resty client
myClientRootCertStr := `-----BEGIN CERTIFICATE----- ... cert content ... -----END CERTIFICATE-----` client.SetClientRootCertificateFromString(myClientRootCertStr)
func (*Client) SetClientRootCertificates ¶
SetClientRootCertificates method helps to add one or more client root certificate files into the Resty client
// one pem file path
client.SetClientRootCertificates("/path/to/client-root/pemFile.pem")
// one or more pem file path(s)
client.SetClientRootCertificates(
"/path/to/client-root/pemFile1.pem",
"/path/to/client-root/pemFile2.pem"
"/path/to/client-root/pemFile3.pem"
)
// if you happen to have string slices
client.SetClientRootCertificates(certs...)
func (*Client) SetClientRootCertificatesWatcher ¶
func (c *Client) SetClientRootCertificatesWatcher(options *CertWatcherOptions, pemFilePaths ...string) *Client
SetClientRootCertificatesWatcher method enables dynamic reloading of one or more client root certificate files. It is designed for scenarios involving long-running Resty clients where certificates may be renewed.
client.SetClientRootCertificatesWatcher(
&resty.CertWatcherOptions{
PoolInterval: 24 * time.Hour,
},
"client-root-ca.pem",
)
func (*Client) SetCloseConnection ¶
SetCloseConnection method sets the http.Request.Close field on each request, instructing the transport to close the connection after the response.
It can be overridden at the request level; see Request.SetCloseConnection.
func (*Client) SetContentDecompresserKeys ¶
SetContentDecompresserKeys method sets given Content-Encoding (RFC 9110) directives into the client instance.
It checks the given Content-Encoding exists in the ContentDecompresser list before assigning it, if it does not exist, it will skip that directive.
Use this method to overwrite the default order. If a new content Decompresser is added, that directive will be the first.
func (*Client) SetContext ¶
SetContext method sets the context on the client instance; it is attached to every Request raised from this client.
func (*Client) SetCookie ¶
SetCookie method appends a single cookie to the client instance. These cookies will be added to all the requests from this client instance.
client.SetCookie(&http.Cookie{
Name:"go-resty",
Value:"This is cookie value",
})
func (*Client) SetCookieJar ¶
SetCookieJar method sets the cookie jar on the client, replacing any existing jar.
For Example, sometimes we don't want to save cookies in API mode so that we can remove the default CookieJar in resty client.
client.SetCookieJar(nil)
func (*Client) SetCookies ¶
SetCookies method sets an array of cookies in the client instance. These cookies will be added to all the requests from this client instance.
cookies := []*http.Cookie{
&http.Cookie{
Name:"go-resty-1",
Value:"This is cookie 1 value",
},
&http.Cookie{
Name:"go-resty-2",
Value:"This is cookie 2 value",
},
}
// Setting a cookies into resty
client.SetCookies(cookies)
func (*Client) SetCurlCmdDebugLog ¶
SetCurlCmdDebugLog method enables the curl command to be logged in the debug log.
It can be overridden at the request level; see Request.SetCurlCmdDebugLog
func (*Client) SetCurlCmdGenerate ¶
SetCurlCmdGenerate method is used to turn on/off the generate curl command at the client instance level.
By default, Resty does not log the curl command in the debug log since it has the potential to leak sensitive data unless explicitly enabled via Client.SetCurlCmdDebugLog or Request.SetCurlCmdDebugLog.
NOTE: Use with care.
- Potential to leak sensitive data from Request and Response in the debug log when the debug log option is enabled.
- Additional memory usage since the request body was reread.
- curl body is not generated for io.Reader and multipart request flow.
It can be overridden at the request level; see Request.SetCurlCmdGenerate
func (*Client) SetDebug ¶
SetDebug method is used to turn on/off the debug mode on the Resty client instance. It logs details of every request and response when enabled.
client.SetDebug(true)
Also, it can be enabled at the request level for a particular request; see Request.SetDebug.
func (*Client) SetDebugBodyLimit ¶
SetDebugBodyLimit sets the maximum size in bytes for which the response and request body will be logged in debug mode.
client.SetDebugBodyLimit(1000000)
func (*Client) SetDebugLogFormatter ¶
func (c *Client) SetDebugLogFormatter(df DebugLogFormatterFunc) *Client
SetDebugLogFormatter method sets the debug log formatter on the client instance.
func (*Client) SetDigestAuth ¶
SetDigestAuth method sets the Digest Auth transport with provided credentials in the client. If a server responds with 401 and sends a Digest challenge in the header `WWW-Authenticate`, the request will be resent with the appropriate digest `Authorization` header.
For Example: To set the Digest scheme with user "Mufasa" and password "Circle Of Life"
client.SetDigestAuth("Mufasa", "Circle Of Life")
Information about Digest Access Authentication can be found in RFC 7616.
NOTE:
- On the QOP `auth-int` scenario, the request body is read into memory to compute the body hash that increases memory usage.
- Create a dedicated client instance to use digest auth, as it does digest auth for all the requests raised by the client.
func (*Client) SetFormData ¶
SetFormData method sets Form parameters and their values in the client instance. The request content type would be set as `application/x-www-form-urlencoded`. The client-level form data gets added to all the requests. Also, it can be overridden at the request level.
See Request.SetFormData.
client.SetFormData(map[string]string{
"access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
"user_id": "3455454545",
})
func (*Client) SetHeader ¶
SetHeader method sets a single header and its value in the client instance. These headers will be applied to all requests raised from the client instance. Also, it can be overridden by request-level header options.
For Example: To set `Content-Type` and `Accept` as `application/json`
client.
SetHeader("Content-Type", "application/json").
SetHeader("Accept", "application/json")
See Request.SetHeader or Request.SetHeaders.
func (*Client) SetHeaderAny ¶
SetHeaderAny method sets a single header field and its value in the client instance for all requests raised from the client.
It is similar to Client.SetHeader but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
For Example: To set `X-Request-Id` with an integer value
client.SetHeaderAny("X-Request-Id", 12345)
See Request.SetHeaderAny or Client.SetHeader.
func (*Client) SetHeaderAuthorizationKey ¶
SetHeaderAuthorizationKey method sets the given HTTP header name for Authorization in the client instance.
It can be overridden at the request level; see Request.SetHeaderAuthorizationKey.
client.SetHeaderAuthorizationKey("X-Custom-Authorization")
func (*Client) SetHeaderVerbatim ¶
SetHeaderVerbatim method is used to set the HTTP header key and value verbatim in the current request. It is typically helpful for legacy applications or servers that require HTTP headers in a certain way
For Example: To set header key as `all_lowercase`, `UPPERCASE`, and `x-cloud-trace-id`
client.
SetHeaderVerbatim("all_lowercase", "available").
SetHeaderVerbatim("UPPERCASE", "available").
SetHeaderVerbatim("x-cloud-trace-id", "798e94019e5fc4d57fbb8901eb4c6cae")
func (*Client) SetHeaderVerbatimAny ¶
SetHeaderVerbatimAny method sets the HTTP header key and value verbatim in the client instance for all requests raised from the client.
It is similar to Client.SetHeaderVerbatim but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
For Example: To set header key as `x-trace-id` with an integer value
client.SetHeaderVerbatimAny("x-trace-id", 798940)
See Request.SetHeaderVerbatimAny or Client.SetHeaderVerbatim.
func (*Client) SetHeaders ¶
SetHeaders method sets multiple headers and their values at one go, and these headers will be applied to all requests raised from the client instance. Also, it can be overridden at request-level headers options.
For Example: To set `Content-Type` and `Accept` as `application/json`
client.SetHeaders(map[string]string{
"Content-Type": "application/json",
"Accept": "application/json",
})
See Request.SetHeaders or Request.SetHeader.
func (*Client) SetHedging ¶
SetHedging method sets the Hedger implementation on the client. Passing nil disables hedging.
See NewHedging for more details about the default Hedging implementation.
func (*Client) SetJSONEscapeHTML ¶
SetJSONEscapeHTML method enables or disables the HTML escape on JSON marshal. By default, escape HTML is `true`.
NOTE: This option only applies to the standard JSON Marshaller used by Resty.
It can be overridden at the request level, see Request.SetJSONEscapeHTML
func (*Client) SetLoadBalancer ¶
func (c *Client) SetLoadBalancer(b LoadBalancer) *Client
SetLoadBalancer method sets the load balancer used for request routing.
func (*Client) SetLogger ¶
SetLogger method sets the logger used by the client for request and response details. The provided value must implement the Logger interface.
func (*Client) SetLoggerWarnLevel ¶
SetLoggerWarnLevel method controls whether warning log messages are emitted. When d is true, warnings are suppressed. For example, Resty normally warns when BasicAuth is used over a non-TLS connection.
client.SetLoggerWarnLevel(true)
func (*Client) SetMethodDeleteAllowPayload ¶
SetMethodDeleteAllowPayload method allows or disallows a payload with the DELETE method. By default, Resty does not allow a payload with DELETE requests.
client.SetMethodDeleteAllowPayload(true)
More info, refer to GH#881
It can be overridden at the request level. See Request.SetMethodDeleteAllowPayload
func (*Client) SetMethodGetAllowPayload ¶
SetMethodGetAllowPayload method allows or disallows a payload with the GET method. By default, Resty does not allow a payload with GET requests.
client.SetMethodGetAllowPayload(true)
It can be overridden at the request level. See Request.SetMethodGetAllowPayload
func (*Client) SetPathParam ¶
SetPathParam method sets a single URL path key-value pair in the Resty client instance.
client.SetPathParam("userId", "sample@sample.com")
Result:
URL - /v1/users/{userId}/details
Composed URL - /v1/users/sample@sample.com/details
It replaces the value of the key while composing the request URL. The value will be escaped using url.PathEscape function.
It can be overridden at the request level, see Request.SetPathParam or Request.SetPathParams
func (*Client) SetPathParamAny ¶
SetPathParamAny method sets a single URL path key-value pair in the Resty client instance.
It is similar to Client.SetPathParam but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
client.SetPathParamAny("userId", 12345)
Result:
URL - /v1/users/{userId}/details
Composed URL - /v1/users/12345/details
It replaces the value of the key while composing the request URL. The value will be escaped using url.PathEscape function.
It can be overridden at the request level, see Request.SetPathParamAny or Request.SetPathParams
func (*Client) SetPathParams ¶
SetPathParams method sets multiple URL path key-value pairs at one go in the Resty client instance.
client.SetPathParams(map[string]string{
"userId": "sample@sample.com",
"subAccountId": "100002",
"path": "groups/developers",
})
Result:
URL - /v1/users/{userId}/{subAccountId}/{path}/details
Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details
It replaces the value of the key while composing the request URL. The values will be escaped using url.PathEscape function.
It can be overridden at the request level, see Request.SetPathParam or Request.SetPathParams
func (*Client) SetPathRawParam ¶
SetPathRawParam method sets a single URL path key-value pair in the Resty client instance without path escape.
client.SetPathRawParam("path", "groups/developers")
Result:
URL - /v1/users/{path}/details
Composed URL - /v1/users/groups/developers/details
It replaces the value of the key while composing the request URL. The value will be used as-is, no path escape applied.
It can be overridden at the request level, see Request.SetPathRawParam or Request.SetPathRawParams
func (*Client) SetPathRawParamAny ¶
SetPathRawParamAny method sets a single URL path key-value pair in the Resty client instance without path escape.
It is similar to Client.SetPathRawParam but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
client.SetPathRawParamAny("userId", 12345)
Result:
URL - /v1/users/{userId}/details
Composed URL - /v1/users/12345/details
It replaces the value of the key while composing the request URL. The value will be used as-is, no path escape applied.
It can be overridden at the request level, see Request.SetPathRawParamAny or Request.SetPathRawParams
func (*Client) SetPathRawParams ¶
SetPathRawParams method sets multiple URL path key-value pairs at one go in the Resty client instance without path escape.
client.SetPathRawParams(map[string]string{
"userId": "sample@sample.com",
"subAccountId": "100002",
"path": "groups/developers",
})
Result:
URL - /v1/users/{userId}/{subAccountId}/{path}/details
Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details
It replaces the value of the key while composing the request URL. The value will be used as-is, no path escape applied.
It can be overridden at the request level, see Request.SetPathRawParam or Request.SetPathRawParams
func (*Client) SetProxy ¶
SetProxy method sets the proxy URL on the client. The proxy type is determined by the URL scheme. "http", "https", and "socks5" are supported. If the scheme is empty, "http" is assumed.
// HTTP/HTTPS proxy
client.SetProxy("http://proxyserver:8888")
// SOCKS5 Proxy
client.SetProxy("socks5://127.0.0.1:1080")
You can also set the Proxy URL using the environment variable `HTTP_PROXY`. See http.ProxyFromEnvironment for more details.
func (*Client) SetQueryParam ¶
SetQueryParam method sets a single parameter and its value in the client instance. It will be formed as a query string for the request.
For Example: `search=kitchen%20papers&size=large`
In the URL after the `?` mark. These query params will be added to all the requests raised from this client instance. Also, it can be overridden at the request level.
See Request.SetQueryParam or Request.SetQueryParams.
client.
SetQueryParam("search", "kitchen papers").
SetQueryParam("size", "large")
func (*Client) SetQueryParamAny ¶
SetQueryParamAny method sets a single query parameter and its value in the client instance. It will be formed as a query string for the request.
It is similar to Client.SetQueryParam but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
For Example: To set `page` and `active` query parameters
client.
SetQueryParamAny("page", 5).
SetQueryParamAny("active", true)
func (*Client) SetQueryParams ¶
SetQueryParams method sets multiple parameters and their values at one go in the client instance. It will be formed as a query string for the request.
For Example: `search=kitchen%20papers&size=large`
In the URL after the `?` mark. These query params will be added to all the requests raised from this client instance. Also, it can be overridden at the request level.
See Request.SetQueryParams or Request.SetQueryParam.
client.SetQueryParams(map[string]string{
"search": "kitchen papers",
"size": "large",
})
func (*Client) SetQueryParamsUnescape ¶
SetQueryParamsUnescape method sets the choice of unescape query parameters for the request URL. To prevent broken URL, Resty replaces space (" ") with "+" in the query parameters.
See Request.SetQueryParamsUnescape
NOTE: Request failure is possible due to non-standard usage of Unescaped Query Parameters.
func (*Client) SetRateLimiter ¶
func (c *Client) SetRateLimiter(l RateLimiter) *Client
SetRateLimiter method sets the RateLimiter on the client. The rate limiter is consulted before every request; if it returns an error the request is aborted with that error.
Use NewRateLimitTokenBucket to create a standard token-bucket limiter, NewRateLimitSlidingWindow for sliding-window semantics, or supply any implementation of the RateLimiter interface for custom strategies.
For example, to allow at most 100 requests per second with a burst of 10:
client.SetRateLimiter(resty.NewRateLimitTokenBucket(100, 10))
Pass nil to remove a previously configured rate limiter.
func (*Client) SetRedirectPolicy ¶
func (c *Client) SetRedirectPolicy(policies ...RedirectPolicy) *Client
SetRedirectPolicy method sets the redirect policy for the client. Resty provides ready-to-use redirect policies. To implement a custom policy, see RedirectPolicy.
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20))
// Need multiple redirect policies together
client.SetRedirectPolicy(resty.FlexibleRedirectPolicy(20), resty.DomainCheckRedirectPolicy("host1.com", "host2.net"))
NOTE: It overwrites the previous redirect policies in the client instance.
func (*Client) SetRequestMiddlewares ¶
func (c *Client) SetRequestMiddlewares(middlewares ...RequestMiddleware) *Client
SetRequestMiddlewares method allows Resty users to override the default request middleware sequence or execution chain.
Method accepts a function of type RequestMiddleware. All the request middlewares are applied; before sending the request to the server.
client.SetRequestMiddlewares( Custom1RequestMiddleware, Custom2RequestMiddleware, resty.PrepareRequestMiddleware, // after this, `Request.RawRequest` instance is available Custom3RequestMiddleware, Custom4RequestMiddleware, )
See Client.AddRequestMiddleware for more details.
NOTE:
- It overwrites the existing request middleware list.
- Be sure to include Resty request middlewares in the request chain at the appropriate spot.
func (*Client) SetResponseBodyLimit ¶
SetResponseBodyLimit method sets a maximum body size limit in bytes on responses to avoid reading too much data into memory.
Client will return resty.ErrResponseBodyTooLarge if the body size of the body in the uncompressed response is larger than the limit. Body size limit will not be enforced in the following cases:
- ResponseBodyLimit <= 0, which is the default behavior.
- Request.SetResponseSaveFileName is called to save response data to the file.
- "DoNotParseResponse" is set for client or request.
It can be overridden at the request level; see Request.SetResponseBodyLimit
func (*Client) SetResponseBodyUnlimitedReads ¶
SetResponseBodyUnlimitedReads method enables or disables in-memory buffering of the response body, allowing unlimited reads.
It can be overridden at the request level; see Request.SetResponseBodyUnlimitedReads
Unlimited reads are possible in a few scenarios, even without enabling it.
- When debug mode is enabled
NOTE: Use with care
- Turning on this feature keeps the response body in memory, which might cause additional memory usage.
func (*Client) SetResponseDoNotParse ¶
SetResponseDoNotParse method instructs Resty not to parse the response body automatically.
Resty exposes the raw response body as io.ReadCloser. If you use it, do not forget to close the body, otherwise, you might get into connection leaks, and connection reuse may not happen.
NOTE: The default Response middlewares are not executed when using this option. User takes over the control of handling response body from Resty.
func (*Client) SetResponseMiddlewares ¶
func (c *Client) SetResponseMiddlewares(middlewares ...ResponseMiddleware) *Client
SetResponseMiddlewares method allows Resty users to override the default response middleware sequence or execution chain.
Method accepts a function of type ResponseMiddleware. All the response middlewares are executed with a Response instance before returning the response to the caller.
client.SetResponseMiddlewares( Custom1ResponseMiddleware, Custom2ResponseMiddleware, resty.AutoParseResponseMiddleware, // before this, the body is not read except on the debug flow Custom3ResponseMiddleware, resty.SaveToFileResponseMiddleware, // See, Request.SetOutputFileName, Request.SetSaveResponse Custom4ResponseMiddleware, Custom5ResponseMiddleware, )
See, Client.AddResponseMiddleware
NOTE:
- It overwrites the existing response middleware list.
- Be sure to include Resty response middlewares in the response chain at the appropriate spot.
func (*Client) SetResponseSaveDirectory ¶
SetResponseSaveDirectory method sets the output directory for saving HTTP responses to file. Resty creates the directory if it does not exist. This setting is optional and can be used together with the absolute path in Request.SetResponseSaveFileName.
client.SetResponseSaveDirectory("/save/http/response/here")
func (*Client) SetResponseSaveToFile ¶
SetResponseSaveToFile method enables or disables saving responses to file for all requests.
client.SetResponseSaveToFile(true)
Resty determines the save filename in the following order -
- Request.SetResponseSaveFileName
- Content-Disposition header
- Request URL using path.Base
- Request URL hostname if path is empty or "/"
It can be overridden at request level, see Request.SetResponseSaveToFile
func (*Client) SetResultError ¶
SetResultError method registers a common error type on the client instance, used for automatic unmarshalling when the response status code is greater than 399 and the content type is JSON or XML. It can be a pointer or a non-pointer.
client.SetResultError(&LoginErrorResponse{})
// OR
client.SetResultError(LoginErrorResponse{})
func (*Client) SetRetryAllowNonIdempotent ¶
SetRetryAllowNonIdempotent method enables or disables retry for non-idempotent HTTP methods. By default, Resty only retries idempotent HTTP methods; see RFC 9110 Section 9.2.2, RFC 9110 Section 18.2
It can be overridden at the request level; see Request.SetRetryAllowNonIdempotent.
func (*Client) SetRetryCount ¶
SetRetryCount method sets the maximum number of retry attempts.
first attempt + retry count = total attempts
See Request.SetRetryDelayStrategy
NOTE:
- By default, Resty only does retry on idempotent HTTP verb, RFC 9110 Section 9.2.2, RFC 9110 Section 18.2
func (*Client) SetRetryDefaultConditions ¶
SetRetryDefaultConditions method enables or disables the built-in retry conditions, which check for transport, header, and URL errors.
Enabled by default.
It can be overridden at the request level; see Request.SetRetryDefaultConditions.
func (*Client) SetRetryDelayStrategy ¶
func (c *Client) SetRetryDelayStrategy(rs RetryDelayStrategyFunc) *Client
SetRetryDelayStrategy method sets a custom RetryDelayStrategyFunc that determines the wait time before each retry attempt. It can be overridden at the request level; see Request.SetRetryDelayStrategy.
By default, Resty uses capped exponential backoff with jitter.
func (*Client) SetRetryMaxWaitTime ¶
SetRetryMaxWaitTime method sets the maximum wait time between retry attempts.
Default is 2 seconds.
func (*Client) SetRetryWaitTime ¶
SetRetryWaitTime method sets the minimum wait time between retry attempts.
Default is 100 milliseconds.
func (*Client) SetRootCertificateFromString ¶
SetRootCertificateFromString method helps to add root certificate from the string into the Resty client
myRootCertStr := `-----BEGIN CERTIFICATE----- ... cert content ... -----END CERTIFICATE-----` client.SetRootCertificateFromString(myRootCertStr)
func (*Client) SetRootCertificates ¶
SetRootCertificates method helps to add one or more root certificate files into the Resty client
// one pem file path
client.SetRootCertificates("/path/to/root/pemFile.pem")
// one or more pem file path(s)
client.SetRootCertificates(
"/path/to/root/pemFile1.pem",
"/path/to/root/pemFile2.pem"
"/path/to/root/pemFile3.pem"
)
// if you happen to have string slices
client.SetRootCertificates(certs...)
func (*Client) SetRootCertificatesWatcher ¶
func (c *Client) SetRootCertificatesWatcher(options *CertWatcherOptions, pemFilePaths ...string) *Client
SetRootCertificatesWatcher method enables dynamic reloading of one or more root certificate files. It is designed for scenarios involving long-running Resty clients where certificates may be renewed.
client.SetRootCertificatesWatcher(
&resty.CertWatcherOptions{
PoolInterval: 24 * time.Hour,
},
"root-ca.pem",
)
func (*Client) SetScheme ¶
SetScheme method sets the URL scheme used by the client when no scheme is present in the request URL.
client.SetScheme("http")
func (*Client) SetTLSClientConfig ¶
SetTLSClientConfig method sets TLSClientConfig for underlying client Transport.
Values supported by https://pkg.go.dev/crypto/tls#Config can be configured.
// Disable SSL cert verification for local development
client.SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true
})
NOTE: This method overwrites existing http.Transport.TLSClientConfig
func (*Client) SetTimeout ¶
SetTimeout method is used to set a timeout for a request raised by the client.
client.SetTimeout(1 * time.Minute)
It can be overridden at the request level. See Request.SetTimeout
NOTE: Resty uses context.WithTimeout on the request, it does not use http.Client.Timeout
func (*Client) SetTrace ¶
SetTrace method is used to turn on/off the trace capability in the Resty client instance. It provides an insight into the request lifecycle using httptrace.ClientTrace.
client := resty.New().SetTrace(true)
resp, err := client.R().Get("https://httpbin.org/get")
fmt.Println("error:", err)
fmt.Println("Trace Info:", resp.Request.TraceInfo())
The method Request.SetTrace is also available to get trace info for a single request.
func (*Client) SetTransport ¶
func (c *Client) SetTransport(transport http.RoundTripper) *Client
SetTransport method sets custom http.Transport or any http.RoundTripper compatible interface implementation in the Resty client.
transport := &http.Transport{
// something like Proxying to httptest.Server, etc...
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}
client.SetTransport(transport)
NOTE:
- If transport is not the type of http.Transport, you may lose the ability to set a few Resty client settings. However, if you implement TLSClientConfiger interface, then TLS client config is possible to set.
- It overwrites the Resty client transport instance and its configurations.
func (*Client) TLSClientConfig ¶
TLSClientConfig method returns the tls.Config from the underlying transport, or nil if the transport does not expose TLS configuration.
func (*Client) Transport ¶
func (c *Client) Transport() http.RoundTripper
Transport method returns the underlying http.RoundTripper used by the client.
type ContentDecompresser ¶
type ContentDecompresser func(io.ReadCloser) (io.ReadCloser, error)
ContentDecompresser wraps an io.ReadCloser response body with decompression based on the Content-Encoding header (RFC 9110). For example, gzip, deflate, etc.
type ContentTypeDecoder ¶
ContentTypeDecoder decodes a response body from the given reader according to the response Content-Type header.
type ContentTypeEncoder ¶
ContentTypeEncoder encodes a request body value into the given writer according to the request Content-Type header.
type DebugLog ¶
type DebugLog struct {
Request *DebugLogRequest `json:"request"`
Response *DebugLogResponse `json:"response"`
TraceInfo *TraceInfo `json:"trace_info"`
}
DebugLog holds the request, response, and optional trace details captured during a single Resty request execution for debug logging.
type DebugLogCallbackFunc ¶
type DebugLogCallbackFunc func(*DebugLog)
DebugLogCallbackFunc is called with the fully-populated DebugLog before Resty formats or writes the debug output. Use it to inspect or mutate the log entry, for example to add custom fields.
See Client.OnDebugLog.
type DebugLogFormatterFunc ¶
DebugLogFormatterFunc formats a DebugLog into a string for debug output. See the built-in implementations DebugLogFormatter and DebugLogJSONFormatter.
type DebugLogRequest ¶
type DebugLogRequest struct {
// CorrelationID is the request correlation ID (see [Request.SetCorrelationID]).
CorrelationID string `json:"correlation_id"`
// Host is the target host of the request.
Host string `json:"host"`
// URI is the request URI including path and query string.
URI string `json:"uri"`
// Method is the HTTP method of the request.
Method string `json:"method"`
// Proto is the HTTP protocol version, e.g. "HTTP/1.1".
Proto string `json:"proto"`
// Header contains the outgoing request headers (sensitive values are redacted).
Header http.Header `json:"header"`
// CurlCmd is the equivalent curl command string, populated when curl command
// generation and debug logging are both enabled.
CurlCmd string `json:"curl_cmd"`
// Attempt is the current attempt number (1 = initial, >1 = retry).
Attempt int `json:"attempt"`
// Body is the request body as a string, truncated to DebugBodyLimit if set.
Body string `json:"body"`
}
DebugLogRequest captures debug information about a Request.
type DebugLogResponse ¶
type DebugLogResponse struct {
// StatusCode is the HTTP response status code.
StatusCode int `json:"status_code"`
// Status is the HTTP response status text, e.g. "200 OK".
Status string `json:"status"`
// Proto is the HTTP protocol version, e.g. "HTTP/1.1".
Proto string `json:"proto"`
// ReceivedAt is the time at which the response was received.
ReceivedAt time.Time `json:"received_at"`
// Duration is the time elapsed from sending the request to receiving the response.
Duration time.Duration `json:"duration"`
// Size is the number of bytes in the response body.
Size int64 `json:"size"`
// Header contains the response headers (sensitive values are redacted).
Header http.Header `json:"header"`
// Body is the response body as a string, truncated to DebugBodyLimit if set.
Body string `json:"body"`
}
DebugLogResponse captures debug information about a Response.
type ErrorHook ¶
ErrorHook is a type used to handle request errors. It’s used as a type in the Client.OnError, Client.OnInvalid, and Client.OPanic hooks.
These hooks are called once during the request and response lifecycle.
type Hedger ¶
type Hedger interface {
http.RoundTripper
// SetTransport sets the underlying HTTP transport that this hedging
// implementation delegates individual requests to.
SetTransport(http.RoundTripper)
// Transport returns the underlying HTTP transport.
Transport() http.RoundTripper
}
Hedger is the interface for implementing a hedging strategy for HTTP requests. Implementations must also implement http.RoundTripper so they can be installed as the HTTP transport on a Client.
The [SetTransport] and [Transport] methods allow Client.SetHedging to wrap and unwrap the underlying transport when hedging is enabled or disabled.
Use NewHedging to create the default implementation (Hedging).
type Hedging ¶
type Hedging struct {
// contains filtered or unexported fields
}
Hedging implements Hedger and http.RoundTripper to perform hedged HTTP requests. It sends multiple requests in parallel with a specified delay and returns the first successful response. Hedging is particularly useful for improving latency in scenarios where requests may occasionally fail or experience high latency.
By default, only read-only HTTP methods (GET, HEAD, OPTIONS, TRACE) are hedged to avoid unintended side effects on the server. Non-read-only methods can be enabled via Hedging.SetNonReadOnlyAllowed.
NOTE:
- Hedging should be used with caution for non-read-only methods, as multiple requests may be processed by the server.
- Ensure the server can safely handle concurrent requests; otherwise, hedging can overwhelm the server.
For more information on hedging and its use cases, see The Tail at Scale.
func NewHedging ¶
func NewHedging() *Hedging
NewHedging creates a new Hedging instance with default configuration. Defaults:
- 50ms delay between requests
- Maximum 3 hedged requests
- Maximum 3 hedged requests per second
- Only read-only methods are hedged
Customize these values with the corresponding setter methods. For example:
hedging := resty.NewHedging(). SetDelay(100 * time.Millisecond). SetMaxRequest(5). SetMaxRequestPerSecond(10) client := resty.New(). SetHedging(hedging) defer client.Close()
func (*Hedging) IsNonReadOnlyAllowed ¶
IsNonReadOnlyAllowed method reports whether hedging is enabled for non-read-only HTTP methods.
func (*Hedging) MaxRequest ¶
MaxRequest method returns the maximum number of concurrent hedged requests.
func (*Hedging) MaxRequestPerSecond ¶
MaxRequestPerSecond method returns the maximum number of hedged requests allowed per second.
func (*Hedging) SetMaxRequest ¶
SetMaxRequest method sets the maximum number of concurrent hedged requests.
func (*Hedging) SetMaxRequestPerSecond ¶
SetMaxRequestPerSecond method sets the maximum number of hedged requests allowed per second.
func (*Hedging) SetNonReadOnlyAllowed ¶
SetNonReadOnlyAllowed method allows hedging for non-read-only HTTP methods. By default, only read-only methods (GET, HEAD, OPTIONS, TRACE) are hedged.
NOTE:
- Use this with caution as hedging write operations can lead to duplicates.
func (*Hedging) SetTransport ¶
func (h *Hedging) SetTransport(t http.RoundTripper)
SetTransport sets the underlying HTTP transport that Hedging delegates individual requests to.
func (*Hedging) Transport ¶
func (h *Hedging) Transport() http.RoundTripper
Transport returns the underlying HTTP transport.
type Host ¶
type Host struct {
// BaseURL represents the targeted host base URL
// https://resty.dev
BaseURL string
// Weight represents the host weight to determine
// the percentage of requests to send
Weight int
// MaxFailures represents the value to mark the host as
// not usable until it reaches the Recovery duration
// Default value is 5
MaxFailures int
// contains filtered or unexported fields
}
Host represents a backend target and its load-balancing parameters.
type HostStateChangeFunc ¶
HostStateChangeFunc is a callback type invoked whenever a host transitions between states. baseURL identifies the host, from is the previous HostState, and to is the new HostState.
type LoadBalancer ¶
type LoadBalancer interface {
NextWithContext(ctx context.Context) (string, error)
Feedback(*RequestFeedback)
Close() error
}
LoadBalancer is the interface that abstracts a load-balancing algorithm. Implementations return the next target base URL for each request and accept feedback about request outcomes so the algorithm can adapt over time.
type Logger ¶
type Logger interface {
Errorf(format string, v ...any)
Warnf(format string, v ...any)
Debugf(format string, v ...any)
}
Logger abstracts Resty's internal logging, giving callers control over where and how log output is written. Implement this interface and register it via Client.SetLogger to supply a custom logger.
type MultipartField ¶
type MultipartField struct {
// Name is the multipart field name expected by the server.
Name string
// FileName is the filename sent to the server.
FileName string
// ContentType is the multipart file content type. It is recommended to set
// this explicitly when known to avoid auto-detection.
ContentType string
// Reader is the [io.Reader] source for multipart upload. It is optional if
// [MultipartField.FilePath] is set.
Reader io.Reader
// FilePath is the file path used for multipart upload. It is optional if
// [MultipartField.Reader] is set.
FilePath string
// FileSize is the file size in bytes, reported via
// [MultipartFieldCallbackFunc].
FileSize int64
// ProgressCallback receives live upload progress details for this field.
//
// NOTE: When using [MultipartField.Reader] with this callback, set
// [MultipartField.FileSize] if known so [MultipartFieldProgress] includes a
// meaningful total size.
ProgressCallback MultipartFieldCallbackFunc
// Values is used to provide ordered multipart form-data values for a field.
//
// It is primarily intended for ordered form field use cases.
Values []string
// contains filtered or unexported fields
}
MultipartField describes a multipart/form-data field and its optional file upload metadata.
func (*MultipartField) Clone ¶
func (mf *MultipartField) Clone() *MultipartField
Clone returns a copy of m, except MultipartField.Reader which is shared.
type MultipartFieldCallbackFunc ¶
type MultipartFieldCallbackFunc func(MultipartFieldProgress)
MultipartFieldCallbackFunc receives live multipart upload progress updates.
type MultipartFieldProgress ¶
MultipartFieldProgress contains upload progress details for a multipart field.
func (MultipartFieldProgress) String ¶
func (mfp MultipartFieldProgress) String() string
String returns the string representation of MultipartFieldProgress.
type RateLimitSlidingWindow ¶
type RateLimitSlidingWindow struct {
// contains filtered or unexported fields
}
RateLimitSlidingWindow is a sliding-window based implementation of RateLimiter. It tracks request timestamps and allows a new request only when the number of requests within the past windowSize is below the configured limit.
This implementation is safe for concurrent use from multiple goroutines. Memory usage is proportional to (limit * average_request_rate * windowSize); old timestamps are automatically evicted as they slide out of the window. Access rate and window size through RateLimitSlidingWindow.Limit and RateLimitSlidingWindow.WindowSize.
Compared to token-bucket: sliding window provides stricter enforcement of the request limit within discrete time windows, while token-bucket focuses on average rate with burst tolerance.
Create instances with NewRateLimitSlidingWindow; do not use the zero value directly.
func NewRateLimitSlidingWindow ¶
func NewRateLimitSlidingWindow(limit int, windowSize time.Duration) *RateLimitSlidingWindow
NewRateLimitSlidingWindow creates a new sliding-window RateLimiter that allows at most limit requests within any rolling window of windowSize duration.
Unlike the token-bucket limiter which refills tokens at a constant rate, the sliding window continuously tracks when requests were made and permits a new request only when fewer than limit requests occurred in the past windowSize duration.
For example, to allow 100 requests per 10 seconds:
rateLimiter := resty.NewRateLimitSlidingWindow(100, 10*time.Second) client := resty.New().SetRateLimiter(rateLimiter)
If limit <= 0, it defaults to 5. If windowSize <= 0, it defaults to 1 second.
func (*RateLimitSlidingWindow) Allow ¶
func (l *RateLimitSlidingWindow) Allow(ctx context.Context) error
Allow blocks until the sliding window permits the next request or the context is done. It returns ErrRateLimitExceeded if the context is cancelled or times out before a slot becomes available.
Performance note: When a slot is available (the common case), Allow returns immediately after evicting out-of-window timestamps. The eviction is O(n) where n is the number of out-of-window timestamps, but typically small due to sliding window semantics. Context cancellation is checked before and during any wait period, respecting cancellation immediately.
func (*RateLimitSlidingWindow) Limit ¶
func (l *RateLimitSlidingWindow) Limit() int
Limit returns the maximum number of requests allowed per window.
func (*RateLimitSlidingWindow) WindowSize ¶
func (l *RateLimitSlidingWindow) WindowSize() time.Duration
WindowSize returns the duration of the sliding window.
type RateLimitTokenBucket ¶
type RateLimitTokenBucket struct {
// contains filtered or unexported fields
}
RateLimitTokenBucket is a token-bucket based implementation of RateLimiter. It implements the standard token-bucket algorithm: tokens refill at a constant rate and each request consumes one token. When no tokens are available, RateLimitTokenBucket.Allow blocks until either a token becomes available or the context expires.
This implementation is safe for concurrent use from multiple goroutines. The token count is internally synchronized; access the rate and burst separately through RateLimitTokenBucket.Rate and RateLimitTokenBucket.Burst.
Create instances with NewRateLimitTokenBucket; do not use the zero value directly.
func NewRateLimitTokenBucket ¶
func NewRateLimitTokenBucket(requestsPerSecond float64, burst int) *RateLimitTokenBucket
NewRateLimitTokenBucket creates a new token-bucket RateLimiter that permits at most requests per second with a burst capacity of burst tokens.
The burst value controls how many requests can be issued instantly; after the burst is exhausted, tokens refill at the rate of request tokens per second.
For example, to allow 100 requests per second with a burst of 10:
rateLimiter := resty.NewRateLimitTokenBucket(100, 10) client := resty.New().SetRateLimiter(rateLimiter)
A burst of 1 enforces strict rate limiting with no burstiness.
If requestsPerSecond <= 0, NewRateLimitTokenBucket defaults to 5 requests per second. If burst <= 0, NewRateLimitTokenBucket defaults to a burst of 1.
func (*RateLimitTokenBucket) Allow ¶
func (l *RateLimitTokenBucket) Allow(ctx context.Context) error
Allow blocks until the rate limiter grants a token or the context is done. It returns ErrRateLimitExceeded if the context is cancelled or times out before a token is available.
Performance note: Timer allocations occur only when tokens are exhausted and waiting is necessary. When tokens are available (the common case), Allow returns immediately without allocating timers. Context deadline and cancellation checks are performed on every iteration, respecting cancellation immediately even during token waits.
func (*RateLimitTokenBucket) Burst ¶
func (l *RateLimitTokenBucket) Burst() int
Burst method returns the maximum burst capacity (maximum token count).
func (*RateLimitTokenBucket) Rate ¶
func (l *RateLimitTokenBucket) Rate() float64
Rate method returns the token refill rate in requests per second.
type RateLimiter ¶
type RateLimiter interface {
// Allow blocks until the rate limiter permits the next request or the
// context is done. It returns [ErrRateLimitExceeded] if the context expires
// or is cancelled before a token is available, and nil when the request may
// proceed. Implementations must be goroutine-safe.
Allow(ctx context.Context) error
}
RateLimiter is the interface that wraps the rate limiting behavior used by Client. Implement this interface to provide custom rate limiting strategies. The Client calls RateLimiter.Allow before every request; if it returns an error the request is aborted with that error.
The context passed to RateLimiter.Allow is the request context, so cancellation or deadline expiry is respected automatically. Implementations must be safe for concurrent use.
type RedirectInfo ¶
type RedirectInfo struct {
// URL is the redirect target URL.
URL string
// StatusCode is the HTTP status code that triggered the redirect.
StatusCode int
}
RedirectInfo records the URL and HTTP status code of a single redirect hop, used to build the redirect history on a Response.
type RedirectPolicy ¶
RedirectPolicy controls redirect behaviour in the Resty client. Implementations can be registered via Client.SetRedirectPolicy.
Apply should return nil to allow the redirect to proceed, or a non-nil error to stop it.
func RedirectDomainCheckPolicy ¶
func RedirectDomainCheckPolicy(hostnames ...string) RedirectPolicy
RedirectDomainCheckPolicy creates a RedirectPolicy that only allows redirects to the specified hostnames. Redirects to any other host are stopped with an error.
client.SetRedirectPolicy(resty.RedirectDomainCheckPolicy("host1.com", "host2.org", "host3.net"))
func RedirectFlexiblePolicy ¶
func RedirectFlexiblePolicy(noOfRedirect int) RedirectPolicy
RedirectFlexiblePolicy creates a RedirectPolicy that allows up to noOfRedirect redirects. Once the limit is reached, the redirect is stopped with an error.
client.SetRedirectPolicy(resty.RedirectFlexiblePolicy(20))
func RedirectHeaderStripSensitivePolicy ¶
func RedirectHeaderStripSensitivePolicy(applyDefault bool, headers ...string) RedirectPolicy
RedirectHeaderStripSensitivePolicy creates a RedirectPolicy that removes selected headers from redirected requests.
If applyDefault is true, it also removes headers that match Resty's built-in sensitive-header filter (for example Authorization, auth, token, etc.). Any headers passed via headers are removed as well.
client.SetRedirectPolicy(resty.RedirectHeaderStripSensitivePolicy( true, "X-Internal-Header", "X-Another-Header", ))
NOTE:
- Use this policy with caution as stripping headers may cause some redirects to fail if the server relies on those headers.
- The default sensitive header filter is based on common patterns and may not cover all cases. Always review which headers are being stripped to avoid unintended consequences.
- If combined with policies that copy headers from previous requests (for example, RedirectFlexiblePolicy and RedirectDomainCheckPolicy), register this policy last in Client.SetRedirectPolicy so stripped headers are not reintroduced later.
func RedirectNoPolicy ¶
func RedirectNoPolicy() RedirectPolicy
RedirectNoPolicy disables all redirects in the Resty client.
client.SetRedirectPolicy(resty.RedirectNoPolicy())
type RedirectPolicyFunc ¶
RedirectPolicyFunc is an adapter that allows an ordinary function with the appropriate signature to be used as a RedirectPolicy.
type Request ¶
type Request struct {
// CorrelationID used to track/relate requests.
// By default, Resty sets a GUID as the correlation ID for requests with retry count > 0.
CorrelationID string
URL string
Method string
AuthToken string
AuthScheme string
QueryParams url.Values
FormData url.Values
PathParams map[string]string
Header http.Header
StartTime time.Time
Body any
Result any
ResultError any
RawRequest *http.Request
Cookies []*http.Cookie
IsDebug bool
IsCloseConnection bool
IsResponseDoNotParse bool
ResponseSaveFileName string
ResponseExpectContentType string
ResponseForceContentType string
DebugBodyLimit int
ResponseBodyLimit int64
IsResponseBodyUnlimitedReads bool
IsTrace bool
IsMethodGetAllowPayload bool
IsMethodDeleteAllowPayload bool
IsDone bool
IsResponseSaveToFile bool
Timeout time.Duration
HeaderAuthorizationKey string
RetryCount int
RetryWaitTime time.Duration
RetryMaxWaitTime time.Duration
RetryDelayStrategy RetryDelayStrategyFunc
IsRetryDefaultConditions bool
IsRetryAllowNonIdempotent bool
Label string
// Attempt provides insights into no. of attempts
// Resty made.
//
// first attempt + retry count = total attempts
Attempt int
// contains filtered or unexported fields
}
Request struct is used to compose and fire individual requests from Resty client. The Request provides an option to override client-level settings and also an option for the request composition.
func (*Request) AddRetryConditions ¶
func (r *Request) AddRetryConditions(conditions ...RetryConditionFunc) *Request
AddRetryConditions method adds one or more retry condition functions into the request. These retry conditions are executed to determine if the request can be retried. The request will retry if any functions return `true`, otherwise return `false`.
NOTE:
- Retry conditions are executed on each retry attempt.
- Default retry conditions are executed first.
- Client-level retry conditions are applied to all requests.
- Request-level retry conditions are executed before client-level retry conditions. See Client.AddRetryConditions, Request.SetRetryConditions
- Once a retry condition returns true, the remaining retry conditions are not executed.
- Retry conditions are executed in the order in which they are added.
func (*Request) AddRetryHooks ¶
func (r *Request) AddRetryHooks(hooks ...RetryHookFunc) *Request
AddRetryHooks method adds one or more side-effecting retry hooks in the request.
NOTE:
- Retry hooks are executed on each retry attempt.
- The request-level retry hooks are executed first before client-level hooks. See Client.AddRetryHooks
- Retry hooks are executed in the order in which they are added.
func (*Request) Clone ¶
Clone returns a deep copy of r with its context changed to ctx. It does clone appropriate fields, reset, and reinitialize, so Request can be used again.
The body is not copied, but it's a reference to the original body.
req := client.R().
SetBody("body").
SetHeader("header", "value")
clonedRequest := req.Clone(context.Background())
func (*Request) Context ¶
Context method returns the request's context.Context. To change the context, use Request.Clone or Request.WithContext.
The returned context is always non-nil; it defaults to the background context.
func (*Request) Delete ¶
Delete method does DELETE HTTP request. It's defined in section 9.3.5 of RFC 9110.
func (*Request) Execute ¶
Execute method performs the HTTP request with the given HTTP method and URL for current Request.
resp, err := client.R().Execute(resty.MethodGet, "http://httpbin.org/get")
func (*Request) Funcs ¶
func (r *Request) Funcs(funcs ...RequestFunc) *Request
Funcs method gets executed on request composition that passes the current request instance to provided RequestFunc, which could be used to apply common/reusable logic to the given request instance.
func addRequestContentType(r *Request) *Request {
return r.SetHeader("Content-Type", "application/json").
SetHeader("Accept", "application/json")
}
func addRequestQueryParams(page, size int) func(r *Request) *Request {
return func(r *Request) *Request {
return r.SetQueryParam("page", strconv.Itoa(page)).
SetQueryParam("size", strconv.Itoa(size)).
SetQueryParam("request_no", strconv.Itoa(int(time.Now().Unix())))
}
}
client.R().
Funcs(addRequestContentType, addRequestQueryParams(1, 100)).
Get("https://localhost:8080/foobar")
func (*Request) Head ¶
Head method does HEAD HTTP request. It's defined in section 9.3.2 of RFC 9110.
func (*Request) Options ¶
Options method does OPTIONS HTTP request. It's defined in section 9.3.7 of RFC 9110.
func (*Request) Patch ¶
Patch method does PATCH HTTP request. It's defined in section 2 of RFC 5789.
func (*Request) Post ¶
Post method does POST HTTP request. It's defined in section 9.3.3 of RFC 9110.
func (*Request) Send ¶
Send method performs the HTTP request using the method and URL already defined for current Request.
res, err := client.R().
SetMethod(resty.MethodGet).
SetURL("http://httpbin.org/get").
Send()
func (*Request) SetAuthScheme ¶
SetAuthScheme method sets the auth token scheme type in the HTTP request.
Example Header value structure:
Authorization: <auth-scheme-value-set-here> <auth-token-value>
For Example: To set the scheme to use OAuth
client.R().SetAuthScheme("OAuth")
// The outcome will be -
Authorization: OAuth <auth-token-value>
Information about Auth schemes can be found in RFC 7235, IANA HTTP Auth schemes
It overrides the `Authorization` scheme set by method Client.SetAuthScheme.
func (*Request) SetAuthToken ¶
SetAuthToken method sets the auth token header(Default Scheme: Bearer) in the current HTTP request. Header example:
Authorization: Bearer <auth-token-value-comes-here>
For Example: To set auth token BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F
client.R().SetAuthToken("BC594900518B4F7EAC75BD37F019E08FBC594900518B4F7EAC75BD37F019E08F")
It overrides the Auth token set by method Client.SetAuthToken.
func (*Request) SetBasicAuth ¶
SetBasicAuth method sets the basic authentication header in the current HTTP request.
For Example:
Authorization: Basic <base64-encoded-value>
To set the header for username "go-resty" and password "welcome"
client.R().SetBasicAuth("go-resty", "welcome")
It overrides the credentials set by method Client.SetBasicAuth.
func (*Request) SetBody ¶
SetBody method sets the request body for the request. It supports various practical needs as easy. It's quite handy and powerful. Supported request body data types are `string`, `[]byte`, `struct`, `map`, `slice` and io.Reader.
Body value can be pointer or non-pointer. Automatic marshalling for JSON and XML content type, if it is `struct`, `map`, or `slice`.
NOTE: io.Reader is processed in bufferless mode while sending a request.
For Example:
`struct` gets marshaled based on the request header `Content-Type`.
client.R().
SetBody(User{
Username: "jeeva@myjeeva.com",
Password: "welcome2resty",
})
'map` gets marshaled based on the request header `Content-Type`.
client.R().
SetBody(map[string]any{
"username": "jeeva@myjeeva.com",
"password": "welcome2resty",
"address": &Address{
Address1: "1111 This is my street",
Address2: "Apt 201",
City: "My City",
State: "My State",
ZipCode: 00000,
},
})
`string` as a body input. Suitable for any need as a string input.
client.R().
SetBody(`{
"username": "jeeva@getrightcare.com",
"password": "admin"
}`)
`[]byte` as a body input. Suitable for raw requests such as file upload, serialize & deserialize, etc.
client.R().
SetBody([]byte("This is my raw request, sent as-is"))
and so on.
func (*Request) SetCloseConnection ¶
SetCloseConnection method sets variable `Close` in HTTP request struct with the given value. More info: https://golang.org/src/net/http/request.go
It overrides the value set at the client instance level, see Client.SetCloseConnection
func (*Request) SetContentLength ¶
SetContentLength method sets the given content length value in the HTTP request. By default, Resty won't set `Content-Length`.
client.R().SetContentLength(3486547657)
func (*Request) SetContentType ¶
SetContentType method is a convenient way to set the header Content-Type in the request
client.R().SetContentType("application/json")
func (*Request) SetContext ¶
SetContext method sets the context.Context for the current Request. It overwrites the current context in the Request instance; it does not affect the Request.RawRequest that was already created.
If you want this method to take effect, use this method before invoking Request.Send, Request.Execute, or one of the HTTP verb methods.
func (*Request) SetCookie ¶
SetCookie method appends a single cookie in the current request instance.
client.R().SetCookie(&http.Cookie{
Name:"go-resty",
Value:"This is cookie value",
})
NOTE: Method appends the Cookie value into existing Cookie even if its already existing.
func (*Request) SetCookies ¶
SetCookies method sets an array of cookies in the current request instance.
cookies := []*http.Cookie{
&http.Cookie{
Name:"go-resty-1",
Value:"This is cookie 1 value",
},
&http.Cookie{
Name:"go-resty-2",
Value:"This is cookie 2 value",
},
}
// Setting a cookies into resty's current request
client.R().SetCookies(cookies)
NOTE: Method appends the Cookie value into existing Cookie even if its already existing.
func (*Request) SetCorrelationID ¶
SetCorrelationID method is used to set the correlation ID for the request
By default, Resty sets a GUID as the correlation ID for requests with retry count > 0.
func (*Request) SetCurlCmdDebugLog ¶
SetCurlCmdDebugLog method enables the curl command to be logged in the debug log for the current request.
It can be overridden at the request level; see Client.SetCurlCmdDebugLog
func (*Request) SetCurlCmdGenerate ¶
SetCurlCmdGenerate method is used to turn on/off the generate curl command for the current request.
By default, Resty does not log the curl command in the debug log since it has the potential to leak sensitive data unless explicitly enabled via Request.SetCurlCmdDebugLog or Client.SetCurlCmdDebugLog.
It overrides the options set by the Client.SetCurlCmdGenerate
NOTE: Use with care.
func (*Request) SetDebug ¶
SetDebug method enables the debug mode on the current request. It logs details of the current request and response.
client.R().SetDebug(true)
It overrides the debug value set at the client instance level.
func (*Request) SetFile ¶
SetFile method sets a single file field name and its path for multipart upload.
Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields
client.R().
SetFile("my_file", "/Users/jeeva/Gas Bill - Sep.pdf")
func (*Request) SetFileReader ¶
SetFileReader method is to set a file using io.Reader for multipart upload.
Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields
client.R().
SetFileReader("profile_img", "my-profile-img.png", bytes.NewReader(profileImgBytes)).
SetFileReader("notes", "user-notes.txt", bytes.NewReader(notesBytes))
func (*Request) SetFiles ¶
SetFiles method sets multiple file field names and their paths for multipart uploads.
Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields
client.R().
SetFiles(map[string]string{
"my_file1": "/Users/jeeva/Gas Bill - Sep.pdf",
"my_file2": "/Users/jeeva/Electricity Bill - Sep.pdf",
"my_file3": "/Users/jeeva/Water Bill - Sep.pdf",
})
func (*Request) SetFormData ¶
SetFormData method sets form parameters and their values in the current request. The request content type would be set as `application/x-www-form-urlencoded`.
client.R().
SetFormData(map[string]string{
"access_token": "BC594900-518B-4F7E-AC75-BD37F019E08F",
"user_id": "3455454545",
})
It overrides the form data value set at the client instance level.
See Request.SetFormDataFromValues for the same field name with multiple values.
func (*Request) SetFormDataFromValues ¶
SetFormDataFromValues method appends multiple form parameters with multi-value (url.Values) at one go in the current request.
client.R().
SetFormDataFromValues(url.Values{
"search_criteria": []string{"book", "glass", "pencil"},
})
It overrides the form data value set at the client instance level.
func (*Request) SetHeader ¶
SetHeader method sets a single header field and its value in the current request.
For Example: To set `Content-Type` and `Accept` as `application/json`.
client.R().
SetHeader("Content-Type", "application/json").
SetHeader("Accept", "application/json")
It overrides the header value set at the client instance level.
func (*Request) SetHeaderAny ¶
SetHeaderAny method sets a single header field and its value in the current request.
It is similar to Request.SetHeader but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
For Example: To set `X-Request-Id` with an integer value
client.R().SetHeaderAny("X-Request-Id", 12345)
It overrides the header value set at the client instance level.
See Client.SetHeaderAny.
func (*Request) SetHeaderAuthorizationKey ¶
SetHeaderAuthorizationKey method sets the given HTTP header name for Authorization in the request.
It overrides the `Authorization` header name set by method Client.SetHeaderAuthorizationKey.
client.R().SetHeaderAuthorizationKey("X-Custom-Authorization")
func (*Request) SetHeaderMultiValues ¶
SetHeaderMultiValues sets multiple header fields and their values as a list of strings in the current request.
For Example: To set `Accept` as `text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8`
client.R().
SetHeaderMultiValues(map[string][]string{
"Accept": []string{"text/html", "application/xhtml+xml", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"},
})
It overrides the header value set at the client instance level.
func (*Request) SetHeaderVerbatim ¶
SetHeaderVerbatim method is used to set the HTTP header key and value verbatim in the current request. It is typically helpful for legacy applications or servers that require HTTP headers in a certain way
For Example: To set header key as `all_lowercase`, `UPPERCASE`, and `x-cloud-trace-id`
client.R().
SetHeaderVerbatim("all_lowercase", "available").
SetHeaderVerbatim("UPPERCASE", "available").
SetHeaderVerbatim("x-cloud-trace-id", "798e94019e5fc4d57fbb8901eb4c6cae")
It overrides the header value set at the client instance level.
func (*Request) SetHeaderVerbatimAny ¶
SetHeaderVerbatimAny method sets the HTTP header key and value verbatim in the current request.
It is similar to Request.SetHeaderVerbatim but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
For Example: To set header key as `x-trace-id` with an integer value
client.R().SetHeaderVerbatimAny("x-trace-id", 798940)
It overrides the header value set at the client instance level.
func (*Request) SetHeaders ¶
SetHeaders method sets multiple header fields and their values at one go in the current request.
For Example: To set `Content-Type` and `Accept` as `application/json`
client.R().
SetHeaders(map[string]string{
"Content-Type": "application/json",
"Accept": "application/json",
})
It overrides the header value set at the client instance level.
func (*Request) SetJSONEscapeHTML ¶
SetJSONEscapeHTML method enables or disables the HTML escape on JSON marshal. By default, escape HTML is `true`.
NOTE: This option only applies to the standard JSON Marshaller used by Resty.
It overrides the value set at the client instance level, see Client.SetJSONEscapeHTML
func (*Request) SetLabel ¶
SetLabel method sets the label for the request, which can be used for logging and debugging purposes. By default, the label is empty.
client.R().SetLabel("GetUserDetails").Get("/users/12345")
In Response middlewares, you can access the label using [Response.Request.Label] Then log the label along with time duration and method to get better insights into the request lifecycle.
func (*Request) SetLogger ¶
SetLogger method sets the Logger used for request and response logging. By default, requests and responses inherit their logger from the client.
Compliant to interface resty.Logger.
It overrides the logger value set at the client instance level.
func (*Request) SetMethodDeleteAllowPayload ¶
SetMethodDeleteAllowPayload method allows the DELETE method with payload on the request level. By default, Resty does not allow.
client.R().SetMethodDeleteAllowPayload(true)
More info, refer to GH#881
It overrides the option set by the Client.SetMethodDeleteAllowPayload
func (*Request) SetMethodGetAllowPayload ¶
SetMethodGetAllowPayload method allows the GET method with payload on the request level. By default, Resty does not allow.
client.R().SetMethodGetAllowPayload(true)
It overrides the option set by the Client.SetMethodGetAllowPayload
func (*Request) SetMultipartBoundary ¶
SetMultipartBoundary method sets the custom multipart boundary for the multipart request. Typically, the `mime/multipart` package generates a random multipart boundary if not provided.
func (*Request) SetMultipartField ¶
func (r *Request) SetMultipartField(fieldName, fileName, contentType string, reader io.Reader) *Request
SetMultipartField method sets custom data with Content-Type using io.Reader for multipart upload.
Resty provides an optional multipart live upload progress callback; see method Request.SetMultipartFields
func (*Request) SetMultipartFields ¶
func (r *Request) SetMultipartFields(fields ...*MultipartField) *Request
SetMultipartFields method sets multiple data fields using io.Reader for multipart upload.
Resty provides an optional multipart live upload progress count in bytes; see MultipartField.ProgressCallback and MultipartFieldProgress
For Example:
client.R().SetMultipartFields(
&resty.MultipartField{
Name: "uploadManifest1",
FileName: "upload-file-1.json",
ContentType: "application/json",
Reader: strings.NewReader(`{"input": {"name": "Uploaded document 1", "_filename" : ["file1.txt"]}}`),
},
&resty.MultipartField{
Name: "uploadManifest2",
FileName: "upload-file-2.json",
ContentType: "application/json",
FilePath: "/path/to/upload-file-2.json",
},
&resty.MultipartField{
Name: "image-file1",
FileName: "image-file1.png",
ContentType: "image/png",
Reader: bytes.NewReader(fileBytes),
ProgressCallback: func(mp MultipartFieldProgress) {
// use the progress details
},
},
&resty.MultipartField{
Name: "image-file2",
FileName: "image-file2.png",
ContentType: "image/png",
Reader: imageFile2, // instance of *os.File
ProgressCallback: func(mp MultipartFieldProgress) {
// use the progress details
},
})
If you have a `slice` of fields already, then call-
client.R().SetMultipartFields(fields...)
func (*Request) SetMultipartFormData ¶
SetMultipartFormData method sets simple form fields on the request and sends them as multipart/form-data.
func (*Request) SetMultipartOrderedFormData ¶
SetMultipartOrderedFormData method appends ordered multipart/form-data values for the same field name.
func (*Request) SetPathParam ¶
SetPathParam method sets a single URL path key-value pair in the Resty current request instance.
client.R().SetPathParam("userId", "sample@sample.com")
Result:
URL - /v1/users/{userId}/details
Composed URL - /v1/users/sample@sample.com/details
client.R().SetPathParam("path", "groups/developers")
Result:
URL - /v1/users/{path}/details
Composed URL - /v1/users/groups%2Fdevelopers/details
It replaces the value of the key while composing the request URL. The values will be escaped using function url.PathEscape.
It overrides the path parameter set at the client instance level.
func (*Request) SetPathParamAny ¶
SetPathParamAny method sets a single URL path key-value pair in the current request instance.
It is similar to Request.SetPathParam but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
client.R().SetPathParamAny("userId", 12345)
Result:
URL - /v1/users/{userId}/details
Composed URL - /v1/users/12345/details
It replaces the value of the key while composing the request URL. The value will be escaped using url.PathEscape function.
It overrides the path parameter set at the client instance level.
func (*Request) SetPathParams ¶
SetPathParams method sets multiple URL path key-value pairs at one go in the Resty current request instance.
client.R().SetPathParams(map[string]string{
"userId": "sample@sample.com",
"subAccountId": "100002",
"path": "groups/developers",
})
Result:
URL - /v1/users/{userId}/{subAccountId}/{path}/details
Composed URL - /v1/users/sample@sample.com/100002/groups%2Fdevelopers/details
It replaces the value of the key while composing the request URL. The values will be escaped using function url.PathEscape.
It overrides the path parameter set at the client instance level.
func (*Request) SetPathRawParam ¶
SetPathRawParam method sets a single URL path key-value pair in the Resty current request instance without path escape.
client.R().SetPathRawParam("userId", "sample@sample.com")
Result:
URL - /v1/users/{userId}/details
Composed URL - /v1/users/sample@sample.com/details
client.R().SetPathRawParam("path", "groups/developers")
Result:
URL - /v1/users/{path}/details
Composed URL - /v1/users/groups/developers/details
It replaces the value of the key while composing the request URL. The value will be used as-is, no path escape applied.
It overrides the raw path parameter set at the client instance level.
func (*Request) SetPathRawParamAny ¶
SetPathRawParamAny method sets a single URL path key-value pair in the current request instance without path escape.
It is similar to Request.SetPathRawParam but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
client.R().SetPathRawParamAny("userId", 12345)
Result:
URL - /v1/users/{userId}/details
Composed URL - /v1/users/12345/details
It replaces the value of the key while composing the request URL. The value will be used as-is, no path escape applied.
It overrides the raw path parameter set at the client instance level.
func (*Request) SetPathRawParams ¶
SetPathRawParams method sets multiple URL path key-value pairs at one go in the Resty current request instance without path escape.
client.R().SetPathParams(map[string]string{
"userId": "sample@sample.com",
"subAccountId": "100002",
"path": "groups/developers",
})
Result:
URL - /v1/users/{userId}/{subAccountId}/{path}/details
Composed URL - /v1/users/sample@sample.com/100002/groups/developers/details
It replaces the value of the key while composing the request URL. The value will be used as-is, no path escape applied.
It overrides the raw path parameter set at the client instance level.
func (*Request) SetQueryParam ¶
SetQueryParam method sets a single parameter and its value in the current request. It will be formed as a query string for the request.
For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark.
client.R().
SetQueryParam("search", "kitchen papers").
SetQueryParam("size", "large")
It overrides the query parameter value set at the client instance level.
func (*Request) SetQueryParamAny ¶
SetQueryParamAny method sets a single query parameter and its value in the current request. It will be formed as a query string for the request.
It is similar to Request.SetQueryParam but accepts any type as the value and converts it to a string using predefined formatting rules (integers, bools, time.Time, etc.).
For Example: To set `page` and `active` query parameters
client.R().
SetQueryParamAny("page", 5).
SetQueryParamAny("active", true)
It overrides the query parameter value set at the client instance level.
func (*Request) SetQueryParams ¶
SetQueryParams method sets multiple parameters and their values at one go in the current request. It will be formed as a query string for the request.
For Example: `search=kitchen%20papers&size=large` in the URL after the `?` mark.
client.R().
SetQueryParams(map[string]string{
"search": "kitchen papers",
"size": "large",
})
It overrides the query parameter value set at the client instance level.
func (*Request) SetQueryParamsFromValues ¶
SetQueryParamsFromValues method appends multiple parameters with multi-value (url.Values) at one go in the current request. It will be formed as query string for the request.
For Example: `status=pending&status=approved&status=open` in the URL after the `?` mark.
client.R().
SetQueryParamsFromValues(url.Values{
"status": []string{"pending", "approved", "open"},
})
It overrides the query parameter value set at the client instance level.
func (*Request) SetQueryParamsUnescape ¶
SetQueryParamsUnescape method sets the choice of unescape query parameters for the request URL. To prevent broken URL, Resty replaces space (" ") with "+" in the query parameters.
This method overrides the value set by Client.SetQueryParamsUnescape
NOTE: Request failure is possible due to non-standard usage of Unescaped Query Parameters.
func (*Request) SetQueryString ¶
SetQueryString method provides the ability to use string as an input to set URL query string for the request.
client.R().
SetQueryString("productId=232&template=fresh-sample&cat=resty&source=google&kw=buy a lot more")
It overrides the query parameter value set at the client instance level.
func (*Request) SetResponseBodyLimit ¶
SetResponseBodyLimit method sets a maximum body size limit in bytes on response, avoid reading too much data to memory.
Client will return [ErrResponseBodyTooLarge] if the body size in the uncompressed response is larger than the limit. Body size limit will not be enforced in the following cases:
- ResponseBodyLimit <= 0, which is the default behavior.
- Request.SetResponseSaveFileName is called to save response data to the file.
- "DoNotParseResponse" is set for client or request.
It overrides the value set at the client instance level, see Client.SetResponseBodyLimit
func (*Request) SetResponseBodyUnlimitedReads ¶
SetResponseBodyUnlimitedReads method is to turn on/off the response body in memory that provides an ability to do unlimited reads.
It overrides the value set at the client level; see Client.SetResponseBodyUnlimitedReads
Unlimited reads are possible in a few scenarios, even without enabling it.
- When debug mode is enabled
NOTE: Use with care
- Turning on this feature keeps the response body in memory, which might cause additional memory usage.
func (*Request) SetResponseDoNotParse ¶
SetResponseDoNotParse method instructs Resty not to parse the response body automatically.
Resty exposes the raw response body as io.ReadCloser. If you use it, do not forget to close the body, otherwise, you might get into connection leaks, and connection reuse may not happen.
NOTE: The default Response middlewares are not executed when using this option. User takes over the control of handling response body from Resty.
func (*Request) SetResponseExpectContentType ¶
SetResponseExpectContentType method allows to provide fallback `Content-Type` for automatic unmarshalling when the `Content-Type` response header is unavailable.
func (*Request) SetResponseForceContentType ¶
SetResponseForceContentType method provides a strong sense of response `Content-Type` for automatic unmarshalling. Resty gives this a higher priority than the `Content-Type` response header.
This means that if both Request.SetResponseForceContentType is set and the response `Content-Type` is available, `SetResponseForceContentType` value will win.
func (*Request) SetResponseSaveFileName ¶
SetResponseSaveFileName method sets the output file for the current HTTP request. The current HTTP response will be saved in the given file. It is similar to the `curl -o` flag.
Absolute path or relative path can be used.
If it is a relative path, then the output file goes under the output directory, as mentioned in the Client.SetResponseSaveDirectory.
client.R().
SetResponseSaveFileName("/Users/jeeva/Downloads/ReplyWithHeader-v5.1-beta.zip").
Get("http://bit.ly/1LouEKr")
NOTE: In this scenario
- [Response.BodyBytes] might be nil.
- Response.Body might have already been read.
func (*Request) SetResponseSaveToFile ¶
SetResponseSaveToFile method used to enable the save response option for the current requests
client.R().SetResponseSaveToFile(true)
Resty determines the save filename in the following order -
- Request.SetResponseSaveFileName
- Content-Disposition header
- Request URL using path.Base
- Request URL hostname if path is empty or "/"
It overrides the value set at the client instance level, see Client.SetResponseSaveToFile
func (*Request) SetResult ¶
SetResult method registers the response `Result` object type for automatic unmarshalling of the HTTP response if the response status code is between 200 and 299, and the content type is either JSON or XML.
Note: Request.SetResult input can be a pointer or non-pointer.
The pointer with handle
authToken := &AuthToken{}
client.R().SetResult(authToken)
// Can be accessed via -
fmt.Println(authToken) OR fmt.Println(response.Result().(*AuthToken))
OR -
The pointer without handle or non-pointer
client.R().SetResult(&AuthToken{})
// OR
client.R().SetResult(AuthToken{})
// Can be accessed via -
fmt.Println(response.Result().(*AuthToken))
func (*Request) SetResultError ¶
SetResultError method registers the response `ResultError` object type for automatic unmarshalling for the request, if the response status code is greater than 399 and the content type is either JSON or XML.
NOTE: Request.SetResultError input can be a pointer or non-pointer.
client.R().SetResultError(&AuthError{})
// OR
client.R().SetResultError(AuthError{})
Accessing an unmarshalled error object from response instance.
response.ResultError().(*AuthError)
If this request ResultError object is nil, it will use the client-level error object type if it is set.
func (*Request) SetRetryAllowNonIdempotent ¶
SetRetryAllowNonIdempotent method is used to enable/disable non-idempotent HTTP methods retry. By default, Resty only allows idempotent HTTP methods, see RFC 9110 Section 9.2.2, RFC 9110 Section 18.2
It overrides value set at the client instance level, see Client.SetRetryAllowNonIdempotent
func (*Request) SetRetryConditions ¶
func (r *Request) SetRetryConditions(conditions ...RetryConditionFunc) *Request
SetRetryConditions method overwrites the retry conditions in the request. These retry conditions are executed to determine if the request can be retried. The request will retry if any function returns `true`, otherwise return `false`.
NOTE:
- It overwrites the existing retry conditions.
- See Request.AddRetryConditions method for more details.
func (*Request) SetRetryCount ¶
SetRetryCount method enables retry on Resty client and allows you to set the retry count.
first attempt + retry count = total attempts
See Request.SetRetryDelayStrategy
NOTE:
- By default, Resty only does retry on idempotent HTTP verb, RFC 9110 Section 9.2.2, RFC 9110 Section 18.2
func (*Request) SetRetryDefaultConditions ¶
SetRetryDefaultConditions method is used to enable/disable the Resty's default retry conditions on request level, that checks transport, headers and URL errors.
By default it is enabled.
It overrides value set at the client instance level, see Client.SetRetryDefaultConditions
func (*Request) SetRetryDelayStrategy ¶
func (r *Request) SetRetryDelayStrategy(rs RetryDelayStrategyFunc) *Request
SetRetryDelayStrategy method used to set the custom Retry delay strategy on request, it is used to get wait time before each retry. It overrides the retry delay strategy set at the client instance level, see Client.SetRetryDelayStrategy
By default, Resty employs the capped exponential backoff with a jitter delay strategy.
func (*Request) SetRetryHooks ¶
func (r *Request) SetRetryHooks(hooks ...RetryHookFunc) *Request
SetRetryHooks method overwrites side-effecting retry hooks in the request.
NOTE:
- It overwrites the existing retry hooks.
- See Request.AddRetryHooks method for more details.
func (*Request) SetRetryMaxWaitTime ¶
SetRetryMaxWaitTime method sets the max wait time for sleep before retrying
Default is 2 seconds.
func (*Request) SetRetryWaitTime ¶
SetRetryWaitTime method sets the default wait time for sleep before retrying
Default is 100 milliseconds.
func (*Request) SetTimeout ¶
SetTimeout method is used to set a timeout for the current request
client.R().SetTimeout(1 * time.Minute)
It overrides the timeout set at the client instance level, See Client.SetTimeout
NOTE: Resty uses context.WithTimeout on the request, it does not use http.Client.Timeout
func (*Request) SetTrace ¶
SetTrace method is used to turn on/off the trace capability at the request level. It provides an insight into the request lifecycle using httptrace.ClientTrace.
client := resty.New()
defer client.Close()
resp, err := client.R().
SetTrace(true).
Get("https://httpbin.org/get")
fmt.Println("Error:", err)
fmt.Println("Trace Info:", resp.Request.TraceInfo())
See Client.SetTrace
func (*Request) Trace ¶
Trace method does TRACE HTTP request. It's defined in section 9.3.8 of RFC 9110.
func (*Request) TraceInfo ¶
TraceInfo method returns trace information for the request. If either Client.SetTrace or Request.SetTrace has not been enabled before the request is made, an empty resty.TraceInfo object is returned.
func (*Request) WithContext ¶
WithContext method returns a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil. It does not affect the Request.RawRequest that was already created.
If you want this method to take effect, use this method before invoking Request.Send, Request.Execute, or one of the HTTP verb methods.
type RequestFeedback ¶
RequestFeedback contains request outcome data reported back to a LoadBalancer implementation.
type RequestFunc ¶
RequestFunc is a function type for extended manipulation of a Request instance.
type RequestMiddleware ¶
RequestMiddleware is a type of middleware that is executed during the request processing phase before Resty sends the request to the server.
It is ideal for:
- Intercept Request instance for manipulation
- Terminate the Request early by returning non-nil error
- etc.
See methods Client.AddRequestMiddleware, Client.SetRequestMiddlewares.
Resty provides some built-in request middlewares such as:
- [PrepareRequestMiddleware]: creates the http.Request instance using the Resty Request instance.
type Response ¶
type Response struct {
Request *Request
Body io.ReadCloser
RawResponse *http.Response
IsRead bool
// CascadeError field used to cascade the response processing and
// middleware execution errors
CascadeError error
// contains filtered or unexported fields
}
Response holds response values for an executed request.
func (*Response) Bytes ¶
Bytes method returns the body of the HTTP response as a byte slice. It returns an empty byte slice if it is nil or the body is zero length.
NOTE:
- Returns an empty byte slice on auto-unmarshal scenarios, unless Client.SetResponseBodyUnlimitedReads or Request.SetResponseBodyUnlimitedReads is enabled.
- Returns an empty byte slice when Client.SetResponseDoNotParse or Request.SetResponseDoNotParse is enabled.
func (*Response) Duration ¶
Duration method returns the end-to-end duration from request start to response completion.
See Response.ReceivedAt to know when the client received a response and see Request.StartTime to know when the client sent the request.
func (*Response) IsStatusFailure ¶
IsStatusFailure method returns true if HTTP status `code >= 400` otherwise false.
Example: 400, 500, etc.
func (*Response) IsStatusSuccess ¶
IsStatusSuccess method returns true if HTTP status `code >= 200 and <= 299` otherwise false.
Example: 200, 201, 204, etc.
func (*Response) ReceivedAt ¶
ReceivedAt method returns the time we received a response from the server for the request.
func (*Response) RedirectHistory ¶
func (r *Response) RedirectHistory() []*RedirectInfo
RedirectHistory method returns redirect history entries with URL and status code.
func (*Response) Result ¶
Result method returns the unmarshalled result response object if it exists, otherwise nil.
client := resty.New()
defer client.Close()
res, err := client.R().
SetBody(User{
Username: "testuser",
Password: "testpass",
}).
SetResult(&LoginResponse{}). // or SetResult(LoginResponse{}).
SetResultError(&LoginErrorResponse{}). // or SetResultError(LoginErrorResponse{}).
Post("https://myapp.com/login")
fmt.Println(err, res)
fmt.Println(res.Result().(*LoginResponse))
fmt.Println(res.ResultError().(*LoginErrorResponse))
func (*Response) ResultError ¶
ResultError method returns the unmarshalled result error object if it exists, otherwise nil.
client := resty.New()
defer client.Close()
res, err := client.R().
SetBody(User{
Username: "testuser",
Password: "testpass",
}).
SetResult(&LoginResponse{}). // or SetResult(LoginResponse{}).
SetResultError(&LoginErrorResponse{}). // or SetResultError(LoginErrorResponse{}).
Post("https://myapp.com/login")
fmt.Println(err, res)
fmt.Println(res.Result().(*LoginResponse))
fmt.Println(res.ResultError().(*LoginErrorResponse))
func (*Response) Size ¶
Size method returns the HTTP response size in bytes.
The HTTP Content-Length header can be unavailable or inaccurate for chunked transfer and compressed responses. Resty captures response size while reading the response body so callers can retrieve the actual processed byte count.
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
func (*Response) String ¶
String method returns the body of the HTTP response as a `string`. It returns an empty string if it is nil or the body is zero length.
NOTE:
- Returns an empty string on auto-unmarshal scenarios, unless Client.SetResponseBodyUnlimitedReads or Request.SetResponseBodyUnlimitedReads is enabled.
- Returns an empty string when Client.SetResponseDoNotParse or Request.SetResponseDoNotParse is enabled.
type ResponseError ¶
ResponseError pairs an error with the Response that triggered it. Neither field should be nil.
func (*ResponseError) Error ¶
func (e *ResponseError) Error() string
func (*ResponseError) Unwrap ¶
func (e *ResponseError) Unwrap() error
type ResponseMiddleware ¶
ResponseMiddleware is a type of middleware that is called after a response has been received. All the response middlewares are executed with a Response instance before returning the response to the caller.
NOTE:
- In v3, all response middleware is executed irrespective of the error. The error details are passed down to the subsequent response middleware through the Response.CascadeError field.
- Before processing your middleware, ensure to check Response.CascadeError.
See methods Client.AddResponseMiddleware, Client.SetResponseMiddlewares.
Resty provides some built-in response middlewares such as:
- [AutoParseResponseMiddleware]: automatically parses the response body into the provided struct in Request.SetResult or Request.SetResultError based on response status code.
- [SaveToFileResponseMiddleware]: saves the response body to a file when [Request.SetOutputFileName] or [Request.SetSaveResponse] is used.
type RetryConditionFunc ¶
RetryConditionFunc is the function type used to decide whether a request should be retried. It receives the response and any execution error from the previous attempt. Either argument may be nil:
- res is nil when no HTTP response was received (e.g. network error)
- err is nil when the request completed without a transport error
type RetryDelayStrategyFunc ¶
RetryDelayStrategyFunc defines a custom retry delay strategy. It receives the response/error from the previous attempt and returns the wait duration before the next retry. By default, Resty uses capped exponential backoff with jitter.
func RetryConstantDelayStrategy ¶
func RetryConstantDelayStrategy(delay time.Duration) RetryDelayStrategyFunc
RetryConstantDelayStrategy returns a RetryDelayStrategyFunc that always returns the specified delay duration.
type RetryHookFunc ¶
RetryHookFunc is a side-effecting function called after each failed attempt and before the next retry. It can be used for logging, metrics, or mutating request state. It receives the same response and error as RetryConditionFunc.
type RoundRobin ¶
type RoundRobin struct {
// contains filtered or unexported fields
}
RoundRobin implements the Round-Robin (RR) load-balancing algorithm.
func NewRoundRobin ¶
func NewRoundRobin(baseURLs ...string) (*RoundRobin, error)
NewRoundRobin creates a Round-Robin (RR) load balancer with the given base URLs.
func (*RoundRobin) Close ¶
func (rr *RoundRobin) Close() error
Close is a no-op for the Round-Robin (RR) load balancer.
func (*RoundRobin) Feedback ¶
func (rr *RoundRobin) Feedback(_ *RequestFeedback)
Feedback is a no-op for the Round-Robin (RR) load balancer.
func (*RoundRobin) NextWithContext ¶
func (rr *RoundRobin) NextWithContext(ctx context.Context) (string, error)
NextWithContext returns the next base URL using the Round-Robin (RR) algorithm and supports context cancellation.
func (*RoundRobin) Refresh ¶
func (rr *RoundRobin) Refresh(baseURLs ...string) error
Refresh method replaces the existing base URL list with the given base URLs.
type SRVWeightedRoundRobin ¶
type SRVWeightedRoundRobin struct {
Service string
Proto string
DomainName string
HttpScheme string
// contains filtered or unexported fields
}
SRVWeightedRoundRobin implements an SRV-backed Weighted Round-Robin (WRR) load balancer.
func NewSRVWeightedRoundRobin ¶
func NewSRVWeightedRoundRobin(service, proto, domainName, httpScheme string) (*SRVWeightedRoundRobin, error)
NewSRVWeightedRoundRobin creates an SRV-backed Weighted Round-Robin (WRR) load balancer.
func (*SRVWeightedRoundRobin) Close ¶
func (swrr *SRVWeightedRoundRobin) Close() error
Close stops the SRV refresh ticker and closes the underlying WRR load balancer.
func (*SRVWeightedRoundRobin) Feedback ¶
func (swrr *SRVWeightedRoundRobin) Feedback(f *RequestFeedback)
Feedback forwards request feedback to the underlying WRR load balancer.
func (*SRVWeightedRoundRobin) NextWithContext ¶
func (swrr *SRVWeightedRoundRobin) NextWithContext(ctx context.Context) (string, error)
NextWithContext returns the next SRV-derived base URL using the underlying Weighted Round-Robin (WRR) algorithm.
func (*SRVWeightedRoundRobin) Refresh ¶
func (swrr *SRVWeightedRoundRobin) Refresh() error
Refresh resolves SRV records and replaces the underlying WRR host list.
func (*SRVWeightedRoundRobin) SetOnStateChange ¶
func (swrr *SRVWeightedRoundRobin) SetOnStateChange(fn HostStateChangeFunc)
SetOnStateChange sets a callback for host state transitions.
func (*SRVWeightedRoundRobin) SetRecoveryDuration ¶
func (swrr *SRVWeightedRoundRobin) SetRecoveryDuration(d time.Duration)
SetRecoveryDuration updates the host recovery interval used by the underlying WRR balancer.
func (*SRVWeightedRoundRobin) SetRefreshDuration ¶
func (swrr *SRVWeightedRoundRobin) SetRefreshDuration(d time.Duration)
SetRefreshDuration changes the SRV refresh interval (default: 180 seconds).
type SSEErrorFunc ¶
type SSEErrorFunc func(error)
SSEErrorFunc is a callback type invoked when an error occurs while processing an SSESource stream.
type SSEMessageFunc ¶
type SSEMessageFunc func(any)
SSEMessageFunc is a callback type used to receive event values from the Server-Sent Events (SSE) stream.
type SSEOpenFunc ¶
SSEOpenFunc is a callback type invoked when Resty establishes a Server-Sent Events (SSE) connection.
type SSERequestFailureFunc ¶
SSERequestFailureFunc is a callback function type invoked when the HTTP request to the SSE endpoint fails to establish or maintain a connection.
type SSESource ¶
type SSESource struct {
// contains filtered or unexported fields
}
SSESource implements the Server-Sent Events (SSE) specification client and consumes a stream from a server endpoint.
func NewSSESource ¶
func NewSSESource() *SSESource
NewSSESource creates a new SSESource with default SSE settings.
sse := NewSSESource().
SetURL("https://sse.dev/test").
OnMessage(
func(e any) {
event := e.(*resty.SSE)
fmt.Println(event)
},
nil, // see method godoc
)
err := sse.Get()
fmt.Println(err)
func (*SSESource) AddEventListener ¶
func (sse *SSESource) AddEventListener(eventName string, ef SSEMessageFunc, result any) *SSESource
AddEventListener method registers a callback to consume messages for a specific event type from the server. The second result argument is optional; it can be used to register the data type for JSON data.
sse.AddEventListener(
"friend_logged_in",
func(e any) {
event := e.(*resty.SSE)
fmt.Println(event)
},
nil,
)
// Receiving JSON data from the server, you can set result type
// to do auto-unmarshal
sse.AddEventListener(
"friend_logged_in",
func(e any) {
event := e.(*UserLoggedIn)
fmt.Println(event)
},
UserLoggedIn{},
)
func (*SSESource) AddHeader ¶
AddHeader method appends a header value on the SSESource instance. If the header key already exists, it appends. These headers will be sent in the request while establishing a connection to the event source
sse.AddHeader("Authorization", "token here").
AddHeader("X-Header", "value")
func (*SSESource) Close ¶
func (sse *SSESource) Close()
Close method closes the SSE connection explicitly.
func (*SSESource) Context ¶
Context method returns the context.Context from the SSE source instance.
The returned context is always non-nil; it defaults to the background context.
func (*SSESource) Get ¶
Get method establishes the connection with the server.
sse := NewSSESource().
SetURL("https://sse.dev/test").
OnMessage(
func(e any) {
event := e.(*resty.SSE)
fmt.Println(event)
},
nil, // see method godoc
)
err := sse.Get()
fmt.Println(err)
func (*SSESource) Logger ¶
Logger method returns the logger instance used by the event source instance.
func (*SSESource) OnError ¶
func (sse *SSESource) OnError(ef SSEErrorFunc) *SSESource
OnError registers a callback that is triggered when an error occurs.
sse.OnError(func(err error) {
fmt.Println("Error occurred:", err)
})
func (*SSESource) OnMessage ¶
func (sse *SSESource) OnMessage(ef SSEMessageFunc, result any) *SSESource
OnMessage method registers a callback to emit every SSE event message from the server. The second result argument is optional; it can be used to register the data type for JSON data.
sse.OnMessage(
func(e any) {
event := e.(*resty.SSE)
fmt.Println("Event message", event)
},
nil,
)
// Receiving JSON data from the server, you can set result type
// to do auto-unmarshal
sse.OnMessage(
func(e any) {
event := e.(*MyData)
fmt.Println(event)
},
MyData{},
)
func (*SSESource) OnOpen ¶
func (sse *SSESource) OnOpen(ef SSEOpenFunc) *SSESource
OnOpen registers a callback that is triggered when a connection is established with the server.
sse.OnOpen(func(url string, resHdr http.Header) {
fmt.Println("I'm connected:", url, resHdr)
})
func (*SSESource) OnRequestFailure ¶
func (sse *SSESource) OnRequestFailure(ef SSERequestFailureFunc) *SSESource
OnRequestFailure registers a callback that is triggered when the HTTP request fails while establishing an SSE connection.
sse.OnRequestFailure(func(err error, res *http.Response) {
fmt.Println("Error and response:", err, res)
})
NOTE:
- Do not forget to close the HTTP response body.
- HTTP response may be nil.
func (*SSESource) SetBody ¶
SetBody method sets the request body for the SSESource connection.
Example: sse.SetBody(bytes.NewReader([]byte(`{"test":"put_data"}`)))
func (*SSESource) SetContext ¶
SetContext method sets the context.Context for the current SSESource. It overwrites the current context in the SSESource instance.
If you want this method to take effect, use this method before invoking SSESource.Get.
func (*SSESource) SetHeader ¶
SetHeader method sets a header and its value on the SSESource instance. It overwrites the header value if the key already exists. These headers will be sent in the request while establishing a connection to the event source
sse.SetHeader("Authorization", "token here").
SetHeader("X-Header", "value")
func (*SSESource) SetLogger ¶
SetLogger method sets the Logger used by the SSE client.
Compliant to interface Logger.
func (*SSESource) SetMethod ¶
SetMethod method sets the HTTP method used for the SSESource connection.
sse.SetMethod("POST"), or sse.SetMethod(resty.MethodPost)
func (*SSESource) SetRetryCount ¶
SetRetryCount method sets the retry count used while establishing an SSE connection with the server.
first attempt + retry count = total attempts
Default is 3
sse.SetRetryCount(10)
func (*SSESource) SetRetryMaxWaitTime ¶
SetRetryMaxWaitTime method sets the maximum wait time before retrying the connection request.
Default is 2 seconds.
NOTE: The server-sent retry value takes precedence if present.
sse.SetRetryMaxWaitTime(3 * time.Second)
func (*SSESource) SetRetryWaitTime ¶
SetRetryWaitTime method sets the default wait time before retrying the connection request.
Default is 100 milliseconds.
NOTE: The server-sent retry value takes precedence if present.
sse.SetRetryWaitTime(1 * time.Second)
func (*SSESource) SetSizeMaxBuffer ¶
SetSizeMaxBuffer method sets the maximum scanner buffer size for the SSE client.
Default is 32kb
sse.SetSizeMaxBuffer(64 * 1024) // 64kb
func (*SSESource) SetTLSClientConfig ¶
SetTLSClientConfig method sets TLS configuration on the underlying client transport.
Values supported by https://pkg.go.dev/crypto/tls#Config can be configured.
// Disable SSL cert verification for local development
sse.SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true
})
NOTE: This method overwrites existing http.Transport.TLSClientConfig
func (*SSESource) SetTransport ¶
func (sse *SSESource) SetTransport(transport http.RoundTripper) *SSESource
SetTransport method sets custom http.Transport or any http.RoundTripper on the underlying client transport.
transport := &http.Transport{
// something like Proxying to httptest.Server, etc...
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}
sse.SetTransport(transport)
NOTE:
- If transport is not the type of http.Transport, you may lose the ability to set a few Resty client settings. However, if you implement TLSClientConfiger interface, then TLS client config is possible to set.
- It overwrites the Resty client transport instance and its configurations.
func (*SSESource) SetURL ¶
SetURL method sets the event-source URL on the SSESource instance.
sse.SetURL("https://sse.dev/test")
func (*SSESource) TLSClientConfig ¶
TLSClientConfig method returns the tls.Config from the underlying client transport, or nil when unavailable.
type SuccessHook ¶
SuccessHook is called after a request completes successfully.
type TLSClientConfiger ¶
type TLSClientConfiger interface {
TLSClientConfig() *tls.Config
SetTLSClientConfig(*tls.Config) error
}
TLSClientConfiger interface is to configure TLS Client configuration on custom transport implemented using http.RoundTripper
type TraceInfo ¶
type TraceInfo struct {
// DNSLookup is the duration that the transport took to perform the DNS lookup.
DNSLookup time.Duration `json:"dns_lookup_time"`
// ConnTime is the duration it took to obtain a successful connection.
ConnTime time.Duration `json:"connection_time"`
// TCPConnTime is the duration it took to establish the TCP connection.
TCPConnTime time.Duration `json:"tcp_connection_time"`
// TLSHandshake is the duration of the TLS handshake.
TLSHandshake time.Duration `json:"tls_handshake_time"`
// ServerTime is the duration from sending the request to receiving the first response byte.
ServerTime time.Duration `json:"server_time"`
// ResponseTime is the duration from the first response byte to the completion of reading the body.
ResponseTime time.Duration `json:"response_time"`
// TotalTime is the total end-to-end duration of the request.
TotalTime time.Duration `json:"total_time"`
// IsConnReused reports whether this connection was previously used for another HTTP request.
IsConnReused bool `json:"is_connection_reused"`
// IsConnWasIdle reports whether this connection was obtained from an idle pool.
IsConnWasIdle bool `json:"is_connection_was_idle"`
// ConnIdleTime is the duration that the connection had been idle before being reused,
// valid only when IsConnWasIdle is true.
ConnIdleTime time.Duration `json:"connection_idle_time"`
// RequestAttempt is the number of the current attempt in the request execution flow,
// where 1 is the initial attempt and values greater than 1 indicate retries.
RequestAttempt int `json:"request_attempt"`
// RemoteAddr is the remote network address of the server.
RemoteAddr string `json:"remote_address"`
}
TraceInfo holds timing and connection details captured during a request via httptrace.ClientTrace. Fields cover DNS lookup, TCP connection, TLS handshake, server processing, and total end-to-end duration.
type TransportSettings ¶
type TransportSettings struct {
// DialerTimeout, default value is `30` seconds.
DialerTimeout time.Duration
// DialerKeepAlive, default value is `30` seconds.
DialerKeepAlive time.Duration
// IdleConnTimeout, default value is `90` seconds.
IdleConnTimeout time.Duration
// TLSHandshakeTimeout, default value is `10` seconds.
TLSHandshakeTimeout time.Duration
// ExpectContinueTimeout, default value is `1` seconds.
ExpectContinueTimeout time.Duration
// ResponseHeaderTimeout, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
ResponseHeaderTimeout time.Duration
// MaxIdleConns, default value is `100`.
MaxIdleConns int
// MaxIdleConnsPerHost, default value is `runtime.GOMAXPROCS(0) + 1`.
MaxIdleConnsPerHost int
// MaxConnsPerHost, default value is no limit.
MaxConnsPerHost int
// DisableKeepAlives, default value is `false`.
DisableKeepAlives bool
// MaxResponseHeaderBytes, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
MaxResponseHeaderBytes int64
// WriteBufferSize, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
WriteBufferSize int
// ReadBufferSize, added to provide ability to
// set value. No default value in Resty, the Go
// HTTP client default value applies.
ReadBufferSize int
}
TransportSettings struct is used to define custom dialer and transport values for the Resty client. Please refer to individual struct fields to know the default values.
Also, refer to https://pkg.go.dev/net/http#Transport for more details.
type WeightedRoundRobin ¶
type WeightedRoundRobin struct {
// contains filtered or unexported fields
}
WeightedRoundRobin implements the Weighted Round-Robin (WRR) load-balancing algorithm. Hosts with higher weights receive a proportionally larger share of requests.
func NewWeightedRoundRobin ¶
func NewWeightedRoundRobin(recovery time.Duration, hosts ...*Host) (*WeightedRoundRobin, error)
NewWeightedRoundRobin creates a Weighted Round-Robin (WRR) load balancer with the given recovery duration and hosts.
func (*WeightedRoundRobin) Close ¶
func (wrr *WeightedRoundRobin) Close() error
Close stops the internal recovery ticker used by the Weighted Round-Robin (WRR) load balancer.
func (*WeightedRoundRobin) Feedback ¶
func (wrr *WeightedRoundRobin) Feedback(f *RequestFeedback)
Feedback method processes a request outcome report for the Weighted Round-Robin(WRR) load balancer.
func (*WeightedRoundRobin) NextWithContext ¶
func (wrr *WeightedRoundRobin) NextWithContext(ctx context.Context) (string, error)
NextWithContext returns the next base URL using the Weighted Round-Robin (WRR) algorithm and supports context cancellation.
func (*WeightedRoundRobin) Refresh ¶
func (wrr *WeightedRoundRobin) Refresh(hosts ...*Host) error
Refresh method replaces the existing host list with the given Host slice.
func (*WeightedRoundRobin) SetOnStateChange ¶
func (wrr *WeightedRoundRobin) SetOnStateChange(fn HostStateChangeFunc)
SetOnStateChange sets a callback for host state transitions.
func (*WeightedRoundRobin) SetRecoveryDuration ¶
func (wrr *WeightedRoundRobin) SetRecoveryDuration(d time.Duration)
SetRecoveryDuration updates the host recovery interval used by the WRR ticker.