inpu

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 24 Imported by: 1

README

Inpu — Easy to use HTTP client in Go

Inpu is a Go HTTP client with a builder pattern that reads like natural sentences. It includes typed query parameters, status-based response handling, pluggable middleware, structured logging, and OpenTelemetry observability.

go get github.com/denizgursoy/inpu

Table of Contents

Quick Start

var filteredTodos []Todo

err := inpu.Get("https://jsonplaceholder.typicode.com/todos").
    QueryBool("completed", true).
    QueryInt("userId", 2).
    OnOk(inpu.ThenUnmarshalJsonTo(&filteredTodos)).
    OnAny(inpu.ThenReturnDefaultError).
    Send()

This sends:

GET https://jsonplaceholder.typicode.com/todos?completed=true&userId=2

If the response is 200, the body is unmarshalled into filteredTodos. Any other status returns an error like called [GET] -> https://jsonplaceholder.typicode.com/todos?completed=true&userId=2 and got 500.

Client

Creating a Client
client := inpu.New().
    BasePath("https://api.example.com").
    TimeOutIn(5 * time.Second).
    AuthToken("eyJhbGciOiJSUzI1NiJ9").
    ContentTypeJson().
    AcceptJson()

New() returns a *Client with a pooled HTTP transport. All configuration methods return *Client for chaining.

Client Configuration
Method Description
BasePath(url) Prepends base URL to every request path
TimeOutIn(d) Sets timeout for all requests from this client
Header(key, val) Adds a header to all requests
AuthBasic(user, pass) Sets Basic auth header
AuthToken(token) Sets Bearer token header
UserAgent(ua) Sets User-Agent header
ContentType(ct) Sets Content-Type header
ContentTypeJson() Sets Content-Type to application/json
ContentTypeXml() Sets Content-Type to application/xml
ContentTypeText() Sets Content-Type to text/plain
ContentTypeHtml() Sets Content-Type to text/html
ContentTypeFormUrlEncoded() Sets Content-Type to application/x-www-form-urlencoded
AcceptJson() Sets Accept to application/json
TlsConfig(cfg) Sets custom *tls.Config
DisableTLSVerification() Skips TLS certificate verification
DisableHTTP2() Forces HTTP/1.1 only
DisableRedirects() Disables automatic redirect following
FollowRedirects(n) Follows up to n redirects
EnableCookies() Enables a cookie jar for the client
Close() Cancels pending requests and closes idle connections
ToStandardClient() Returns the underlying *http.Client
Reusable Client
client := inpu.New().
    BasePath("https://jsonplaceholder.typicode.com").
    Use(inpu.RetryMiddleware(2)).
    QueryInt("foo", 1).
    QueryString("foo1", "bar1").
    Header("foo", "bar").
    AuthToken("eyJhbGciOiJSUzI1NiJ9")

err := client.Get("/todos/1").Send()
err = client.Patch("/todos/1", inpu.BodyJson(payload)).Send()
err = client.Post("/todos", inpu.BodyJson(payload)).Send()
err = client.Put("/todos/1", inpu.BodyJson(payload)).Send()

The client above prepends the base path, adds query parameters foo=1&foo1=bar1, sets header Foo: bar, and includes the Bearer token on every request.

Requests

HTTP Methods

Package-level functions (use a default shared client):

inpu.Get(url)
inpu.Post(url, body)
inpu.Put(url, body)
inpu.Patch(url, body)
inpu.Delete(url, body)
inpu.Head(url)

Client methods (use the configured client):

client.Get(url)
client.Post(url, body)
client.Put(url, body)
client.Patch(url, body)
client.Delete(url, body)
client.Head(url)
Context-Aware Methods

Every HTTP method has a *Ctx variant that accepts a context.Context as the first argument:

inpu.GetCtx(ctx, url)
client.GetCtx(ctx, url)
client.PostCtx(ctx, url, body)
// ... and so on for Put, Patch, Delete, Head
Request Headers and Auth

These are available on both *Client and *Req:

req := inpu.Get("https://api.example.com/items").
    Header("X-Custom", "value").
    AuthToken("eyJhbGciOiJSUzI1NiJ9").
    AuthBasic("user", "pass").
    ContentTypeJson().
    AcceptJson().
    UserAgent("my-app/1.0")
Request Timeout
req := inpu.Get("https://api.example.com/items").
    TimeOutIn(3 * time.Second)

This sets a per-request timeout independent of the client timeout.

Query Parameters

Typed query parameter methods are available on both *Client and *Req:

inpu.Get("https://example.com/search").
    QueryString("q", "golang").
    QueryInt("page", 1).
    QueryBool("active", true).
    QueryFloat64("score", 3.14).
    Send()

Full list of types: QueryString, QueryInt, QueryInt8, QueryInt16, QueryInt32, QueryInt64, QueryUint, QueryUint8, QueryUint16, QueryUint32, QueryUint64, QueryFloat32, QueryFloat64, QueryBool.

Every type also has a *Ptr variant (e.g. QueryIntPtr, QueryStringPtr) that accepts a pointer and is a no-op when the pointer is nil. This is useful for optional filter parameters.

Request Bodies

Request body must implement the Requester interface. Use the built-in constructors:

inpu.BodyJson(body any)                       // marshals to JSON
inpu.BodyXml(body any)                        // marshals to XML
inpu.BodyString(body string)                  // plain string
inpu.BodyReader(body io.Reader)               // raw reader
inpu.BodyFormData(body map[string][]string)   // URL-encoded form data
inpu.BodyFormDataFromMap(body map[string]string) // simplified form data

Response Handling

Shorthand Methods

Every status matcher has a corresponding shorthand method on the request. These read like natural sentences:

OnOk(inpu.ThenUnmarshalJsonTo(&result)).          // on 200, unmarshal JSON
OnCreated(inpu.ThenDoNothing).                     // on 201, do nothing
OnNotFound(inpu.ThenReturnError(ErrItemNotFound)). // on 404, return custom error
OnUnauthorized(inpu.ThenReturnError(ErrNoAuth)).   // on 401, return custom error
OnSuccess(inpu.ThenUnmarshalJsonTo(&result)).      // on any 2xx, unmarshal JSON
OnClientError(inpu.ThenReturnDefaultError).        // on any 4xx, return default error
OnServerError(inpu.ThenReturnDefaultError).        // on any 5xx, return default error
OnAny(inpu.ThenReturnDefaultError).                // fallback for any status
OnAnyExcept(http.StatusOK, inpu.ThenReturnDefaultError). // any status except 200

Parameterized shorthands:

On(http.StatusOK, inpu.ThenUnmarshalJsonTo(&result)).                                  // match a single status code
OnOneOf(inpu.ThenDoNothing, http.StatusOK, http.StatusCreated, http.StatusAccepted).   // match any of several codes
OnAnyExceptOneOf(inpu.ThenReturnDefaultError, http.StatusOK, http.StatusCreated).      // match any except several codes

Available shorthand methods for individual status codes:

1xx Informational 2xx Success 3xx Redirection 4xx Client Error 5xx Server Error
OnContinue (100) OnOk (200) OnMultipleChoices (300) OnBadRequest (400) OnInternalServerError (500)
OnSwitchingProtocols (101) OnCreated (201) OnMovedPermanently (301) OnUnauthorized (401) OnNotImplemented (501)
OnProcessing (102) OnAccepted (202) OnFound (302) OnPaymentRequired (402) OnBadGateway (502)
OnEarlyHints (103) OnNonAuthoritativeInfo (203) OnSeeOther (303) OnForbidden (403) OnServiceUnavailable (503)
OnNoContent (204) OnNotModified (304) OnNotFound (404) OnGatewayTimeout (504)
OnResetContent (205) OnUseProxy (305) OnMethodNotAllowed (405) OnHTTPVersionNotSupported (505)
OnPartialContent (206) OnTemporaryRedirect (307) OnNotAcceptable (406) OnVariantAlsoNegotiates (506)
OnMultiStatus (207) OnPermanentRedirect (308) OnProxyAuthRequired (407) OnInsufficientStorage (507)
OnAlreadyReported (208) OnRequestTimeout (408) OnLoopDetected (508)
OnIMUsed (226) OnConflict (409) OnNotExtended (510)
OnGone (410) OnNetworkAuthenticationRequired (511)
OnLengthRequired (411)
OnPreconditionFailed (412)
OnRequestEntityTooLarge (413)
OnRequestURITooLong (414)
OnUnsupportedMediaType (415)
OnRequestedRangeNotSatisfiable (416)
OnExpectationFailed (417)
OnTeapot (418)
OnMisdirectedRequest (421)
OnUnprocessableEntity (422)
OnLocked (423)
OnFailedDependency (424)
OnTooEarly (425)
OnUpgradeRequired (426)
OnPreconditionRequired (428)
OnTooManyRequests (429)
OnRequestHeaderFieldsTooLarge (431)
OnUnavailableForLegalReasons (451)

Category-level shorthands: OnSuccess, OnInformational, OnRedirection, OnClientError, OnServerError

Wildcard shorthands: OnAny, OnAnyExcept, OnAnyExceptOneOf

On (Advanced Usage)

On provides full control over status matching. Use it when combining matchers with Not() or for other advanced patterns:

err := inpu.Get("https://api.example.com/items").
    On(inpu.StatusIsSuccess, inpu.ThenUnmarshalJsonTo(&items)).
    On(inpu.Not(inpu.StatusIsSuccess), inpu.ThenReturnDefaultError).
    Send()

Status matchers have priorities. When multiple matchers match, the one with the lowest priority value wins. Priorities: StatusIs (1), StatusIsOneOf (2), category matchers like StatusIsSuccess (3), StatusAnyExcept (8), StatusAnyExceptOneOf (9), StatusAny (10).

Available status matchers:

StatusAny                              // matches any status code
StatusAnyExcept(statusCode int)        // matches any except the one provided
StatusAnyExceptOneOf(statusCodes ...int) // matches any except those provided
StatusIsSuccess                        // matches 2xx
StatusIsInformational                  // matches 1xx
StatusIsRedirection                    // matches 3xx
StatusIsClientError                    // matches 4xx
StatusIsServerError                    // matches 5xx
StatusIsOneOf(statusCodes ...int)      // matches any in the provided list
StatusIs(expectedStatus int)           // matches a specific status code
// Plus individual status matchers: StatusIsOk, StatusIsCreated, StatusIsNotFound, etc.
Response Handlers
ThenUnmarshalJsonTo(target any)                        // unmarshals the response body JSON into the pointer provided
ThenUnmarshalJsonAndReturnError(target any, err error) // unmarshals JSON and returns the provided error
ThenReturnError(err error)                             // returns the provided error
ThenReturnDefaultError                                 // returns an error with method, URL, and status code
ThenDoNothing                                          // returns nil (placeholder)

Note: ThenReturnDefaultError and ThenDoNothing are ResponseHandler values, not factories. Pass them without parentheses. ThenUnmarshalJsonTo, ThenUnmarshalJsonAndReturnError, and ThenReturnError are factories that return a ResponseHandler.

Custom Handlers

You can pass any func(r *http.Response) error as a handler:

err := inpu.Get("https://api.example.com/items").
    OnOk(func(r *http.Response) error {
        // custom processing
        return nil
    }).
    Send()

Middlewares

Add middlewares to a client with Use(). Middlewares are sorted by priority (lower = closer to transport).

client := inpu.New().
    Use(inpu.RetryMiddleware(2)).
    Use(inpu.LoggingMiddleware(true, false)).
    Use(inpu.RequestIDMiddleware())
Built-in Middlewares
Middleware Priority Description
LoggingMiddleware(verbose, disabled) 1 Logs requests/responses. Masks sensitive headers.
RequestIDMiddleware() 100 Adds X-Request-ID header and stores ID in context
ErrorHandlerMiddleware(handler) 50 Calls handler on connection errors
RetryMiddleware(maxRetries) 25 Retries on server errors and 429 with exponential backoff
Retry Configuration
client := inpu.New().Use(inpu.RetryMiddlewareWithConfig(inpu.RetryConfig{
    MaxRetries:        3,
    InitialBackoff:    500 * time.Millisecond,
    MaxBackoff:        30 * time.Second,
    BackoffMultiplier: 2.0,
    CustomRetryChecker: func(resp *http.Response, err error) bool {
        // custom retry logic
        return false
    },
}))

The retry middleware respects the Retry-After header on 429 and 503 responses. It retries on server errors (5xx, except 501/505/508/506/511) and 429. TLS certificate errors are never retried.

Custom Middleware

Implement the Middleware interface:

type Middleware interface {
    ID() string
    Priority() int
    Apply(next http.RoundTripper) http.RoundTripper
}

Or use the helper constructors:

// Modify outgoing requests
mw := inpu.RequestModifierMiddleware(
    func(req *http.Request) (*http.Request, error) {
        req.Header.Set("X-Custom", "value")
        return req, nil
    },
    "my-request-modifier", // unique ID
    50,                    // priority
)

// Modify incoming responses
mw := inpu.ResponseModifierMiddleware(
    func(resp *http.Response, err error) (*http.Response, error) {
        // inspect or modify the response
        return resp, err
    },
    "my-response-modifier",
    50,
)
OpenTelemetry
go get github.com/denizgursoy/inpu/middlewares/otel
import inpuotel "github.com/denizgursoy/inpu/middlewares/otel"

client := inpu.New().Use(inpuotel.NewMiddleware())

The OTel middleware (priority 2) sits inside the retry loop, so each attempt gets its own metrics and span.

Options:

Option Description
WithMeterProvider(mp) Use a custom MeterProvider (default: global)
WithTracerProvider(tp) Use a custom TracerProvider (default: global)
WithPropagator(p) Use a custom TextMapPropagator (default: global)
WithoutMetrics() Disable metric collection
WithoutTracing() Disable tracing and context propagation

Collected metrics:

Metric Type Unit Description
http.client.request.duration Float64Histogram s Duration of each request attempt
http.client.request.body.size Int64Histogram By Request body size
http.client.response.body.size Int64Histogram By Response body size
http.client.active_requests Int64UpDownCounter {request} Number of in-flight requests
http.client.request.total Int64Counter {request} Total requests
http.client.request.retry.count Int64Counter {retry} Total retries (attempt > 0)

Attributes: http.request.method, server.address, url.scheme, server.port, http.response.status_code, http.resend_count, inpu.request.id (when RequestIDMiddleware is used), error.type (on errors).

Tracing: Each request attempt creates a client span named METHOD hostname. Trace context is automatically injected into outgoing request headers via the configured propagator. Spans are marked as error for 4xx/5xx responses.

OAuth2 Client Credentials
go get github.com/denizgursoy/inpu/middlewares/oauth2
import inpuoauth2 "github.com/denizgursoy/inpu/middlewares/oauth2"

client := inpu.New().Use(inpuoauth2.NewClientCredentialsMiddleware(
    clientcredentials.Config{
        ClientID:     "my-client-id",
        ClientSecret: "my-client-secret",
        TokenURL:     "https://auth.example.com/oauth/token",
    },
))

Automatically obtains and refreshes OAuth2 tokens using the client credentials flow (priority 75).

Logging

Logger Interface
type Logger interface {
    Error(ctx context.Context, err error, msg string, fields ...any)
    Warn(ctx context.Context, msg string, fields ...any)
    Info(ctx context.Context, msg string, fields ...any)
    Debug(ctx context.Context, msg string, fields ...any)
}
Built-in Logger (slog)

The default logger uses log/slog with JSON output:

logger := inpu.NewInpuLoggerFromSlog(inpu.LogLevelInfo) // LogLevelDebug, LogLevelWarn, LogLevelError
Zap Adapter
go get github.com/denizgursoy/inpu/loggers/zap
import inpuzap "github.com/denizgursoy/inpu/loggers/zap"

logger := inpuzap.NewInpuLoggerFromZapLogger(zapLogger)
Zerolog Adapter
go get github.com/denizgursoy/inpu/loggers/zero
import inpuzero "github.com/denizgursoy/inpu/loggers/zero"

logger := inpuzero.NewInpuLoggerFromZeroLog()
Context Logger Injection

Inject a logger into the context so middlewares use it:

ctx := inpu.ContextWithLogger(ctx, logger)
err := inpu.GetCtx(ctx, "https://api.example.com/items").Send()

Retrieve it with inpu.ExtractLoggerFromContext(ctx). The logging middleware and built-in logger automatically include request_id when RequestIDMiddleware is active.

Errors

Sentinel errors returned by inpu:

Error Description
ErrRequestCreationFailed Could not create the HTTP request
ErrInvalidBody Could not create the request body
ErrConnectionFailed Connection to the server failed
ErrCouldNotParseBaseUrl Invalid base path URL
ErrCouldNotParsePath Invalid request path
ErrMarshalToNil Tried to unmarshal into nil
ErrNotPointerParameter Tried to unmarshal into non-pointer type

DefaultError is returned by ThenReturnDefaultError and formats as called [METHOD] -> URL and got STATUS_CODE.

Utilities

// Extract request ID from context (set by RequestIDMiddleware)
inpu.ExtractRequestIDFromContext(ctx) // returns *string

// Extract retry attempt number from context (set by RetryMiddleware)
inpu.ExtractRetryAttemptFromContext(ctx) // returns int (0 for first attempt)

// Pre-configured HTTP clients and transports
inpu.DefaultPooledClient()    // reusable client with connection pooling
inpu.DefaultClient()          // client with no keepalives
inpu.DefaultPooledTransport() // transport with connection pooling
inpu.DefaultTransport()       // transport with no keepalives

// Auth header helpers
inpu.GetTokenHeaderValue(token)              // returns "Bearer <token>"
inpu.GetBasicAuthHeaderValue(user, password) // returns "Basic <base64>"

// Response body helper
inpu.DrainBodyAndClose(resp) // drains and closes the response body

The package also exports Header* constants (e.g. HeaderContentType, HeaderAuthorization, HeaderXRequestID) and MimeType* constants (e.g. MimeTypeJson, MimeTypeXml, MimeTypeFormUrlEncoded).

Documentation

Index

Constants

View Source
const (
	BasicAuthentication  = "Basic "
	BearerAuthentication = "Bearer "
)
View Source
const (
	ContextKeyRequestID = "inpu_request_id"
	ContextKeyLogger    = "inpu_logger"
)
View Source
const (
	// Content and Accept headers
	HeaderAccept          = "Accept"
	HeaderAcceptCharset   = "Accept-Charset"
	HeaderAcceptEncoding  = "Accept-Encoding"
	HeaderAcceptLanguage  = "Accept-Language"
	HeaderContentType     = "Content-Type"
	HeaderContentLength   = "Content-Length"
	HeaderContentEncoding = "Content-Encoding"

	// Authentication headers
	HeaderAuthorization = "Authorization"
	HeaderAPIKey        = "X-Api-Key"
	HeaderAPISecret     = "X-Api-Secret"
	HeaderAPIToken      = "X-Api-Token"

	// Retry
	HeaderRetryAfter = "Retry-After"

	// Client identification
	HeaderUserAgent = "User-Agent"
	HeaderReferer   = "Referer"
	HeaderOrigin    = "Origin"

	// Caching and conditional requests
	HeaderCacheControl      = "Cache-Control"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfMatch           = "If-Match"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	HeaderIfRange           = "If-Range"

	// Request control
	HeaderExpect     = "Expect"
	HeaderRange      = "Range"
	HeaderHost       = "Host"
	HeaderConnection = "Connection"
	HeaderUpgrade    = "Upgrade"
	HeaderTE         = "TE"

	// Cookies and session
	HeaderCookie = "Cookie"

	// Request tracking and tracing
	HeaderXRequestID     = "X-Request-ID"
	HeaderXCorrelationID = "X-Correlation-ID"
	HeaderXTraceID       = "X-Trace-ID"
	HeaderXSpanID        = "X-Span-ID"

	// Custom client headers
	HeaderXClientVersion = "X-Client-Version"
	HeaderXClientName    = "X-Client-Name"
	HeaderXForwardedFor  = "X-Forwarded-For"
	HeaderXRealIP        = "X-Real-IP"

	// Security headers (client-side)
	HeaderXCSRFToken     = "X-Csrf-Token"
	HeaderXRequestedWith = "X-Requested-With"

	// Common API headers
	HeaderXAPIVersion = "X-Api-Version"
	HeaderXClientID   = "X-Client-ID"
	HeaderXSessionID  = "X-Session-ID"
	HeaderXTenantID   = "X-Tenant-ID"
)
View Source
const (
	// Text types
	MimeTypeText       = "text/plain"
	MimeTypeHtml       = "text/html"
	MimeTypeCss        = "text/css"
	MimeTypeJavascript = "text/javascript"
	MimeTypeCsv        = "text/csv"
	MimeTypeTextXml    = "text/xml"
	MimeTypeCalendar   = "text/calendar"

	// Application types
	MimeTypeJson              = "application/json"
	MimeTypeApplicationXml    = "application/xml"
	MimeTypeFormUrlEncoded    = "application/x-www-form-urlencoded"
	MimeTypeMultipartFormData = "multipart/form-body"
	MimeTypeOctetStream       = "application/octet-stream"
	MimeTypePdf               = "application/pdf"
	MimeTypeZip               = "application/zip"
	MimeTypeGzip              = "application/gzip"
	MimeTypeTar               = "application/x-tar"
	MimeTypeRar               = "application/vnd.rar"
	MimeType7z                = "application/x-7z-compressed"
	MimeTypeJsonApi           = "application/vnd.api+json"
	MimeTypeJsonPatch         = "application/json-patch+json"
	MimeTypeJsonMergePatch    = "application/merge-patch+json"

	// Image types
	MimeTypeJpeg = "image/jpeg"
	MimeTypePng  = "image/png"
	MimeTypeGif  = "image/gif"
	MimeTypeWebp = "image/webp"
	MimeTypeSvg  = "image/svg+xml"
	MimeTypeBmp  = "image/bmp"
	MimeTypeIco  = "image/x-icon"
	MimeTypeTiff = "image/tiff"
	MimeTypeAvif = "image/avif"

	// Audio types
	MimeTypeMp3  = "audio/mpeg"
	MimeTypeWav  = "audio/wav"
	MimeTypeOgg  = "audio/ogg"
	MimeTypeAac  = "audio/aac"
	MimeTypeFlac = "audio/flac"
	MimeTypeM4a  = "audio/mp4"

	// Video types
	MimeTypeMp4  = "video/mp4"
	MimeTypeAvi  = "video/x-msvideo"
	MimeTypeMov  = "video/quicktime"
	MimeTypeWmv  = "video/x-ms-wmv"
	MimeTypeFlv  = "video/x-flv"
	MimeTypeWebm = "video/webm"
	MimeTypeMkv  = "video/x-matroska"

	// Font types
	MimeTypeWoff  = "font/woff"
	MimeTypeWoff2 = "font/woff2"
	MimeTypeTtf   = "font/ttf"
	MimeTypeOtf   = "font/otf"
	MimeTypeEot   = "application/vnd.ms-fontobject"

	// Microsoft Office
	MimeTypeDocx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
	MimeTypeDoc  = "application/msword"
	MimeTypeXlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	MimeTypeXls  = "application/vnd.ms-excel"
	MimeTypePptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
	MimeTypePpt  = "application/vnd.ms-powerpoint"

	// Other common types
	MimeTypeRtf  = "application/rtf"
	MimeTypeSwf  = "application/x-shockwave-flash"
	MimeTypeAtom = "application/atom+xml"
	MimeTypeRss  = "application/rss+xml"
	MimeTypeYaml = "application/x-yaml"
	MimeTypeToml = "application/toml"
)
View Source
const ContextKeyRetryAttempt = "inpu_retry_attempt"
View Source
const LoggerKeyRequestID = "request_id"

Variables

View Source
var (
	ErrRequestCreationFailed = errors.New("could not create the request")
	ErrInvalidBody           = errors.New("could not create the body")
	ErrConnectionFailed      = errors.New("connection failed")
	ErrCouldNotParseBaseUrl  = errors.New("invalid base path")
	ErrCouldNotParsePath     = errors.New("invalid path")
	ErrMarshalToNil          = errors.New("cannot unmarshal to nil")
	ErrNotPointerParameter   = errors.New("cannot marshal to non pointer type ")
)
View Source
var Not = func(matcher StatusMatcher) *statusChecker {
	return &statusChecker{
		matcher: func(statusCode int) bool {
			return !matcher.Match(statusCode)
		},
		priority: matcher.Priority(),
	}
}
View Source
var StatusAny = newStatusChecker(func(_ int) bool {
	return true
}, 10)

StatusAny matches any status code. It can be used as fallback in case previous On matches is not called It has the least priority 10, and it is checked after StatusAnyExceptOneOf Usage: On(StatusAny,func(r *http.Response) error{})

View Source
var StatusIsAccepted = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusAccepted
}, 1)

StatusIsAccepted checks if the response status is 202 Accepted. It has the priority 1, and it has the top priority. Usage: On(StatusIsAccepted, func(r *http.Response) error{}) -> only matches when the status code is 202

View Source
var StatusIsAlreadyReported = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusAlreadyReported
}, 1)

StatusIsAlreadyReported checks if the response status is 208 Already Reported. It has the priority 1, and it has the top priority. Usage: On(StatusIsAlreadyReported, func(r *http.Response) error{}) -> only matches when the status code is 208

View Source
var StatusIsBadGateway = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusBadGateway
}, 1)

StatusIsBadGateway checks if the response status is 502 Bad Gateway. It has the priority 1, and it has the top priority. Usage: On(StatusIsBadGateway, func(r *http.Response) error{}) -> only matches when the status code is 502

View Source
var StatusIsBadRequest = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusBadRequest
}, 1)

StatusIsBadRequest checks if the response status is 400 Bad Request. It has the priority 1, and it has the top priority. Usage: On(StatusIsBadRequest, func(r *http.Response) error{}) -> only matches when the status code is 400

View Source
var StatusIsClientError = newStatusChecker(func(statusCode int) bool {
	return statusCode >= http.StatusBadRequest && statusCode < http.StatusInternalServerError
}, 3)

StatusIsClientError checks if the response status code is between [400,500). It has the priority 3, and it is checked after StatusIsOneOf. Usage: On(StatusIsClientError,func(r *http.Response) error{})

View Source
var StatusIsConflict = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusConflict
}, 1)

StatusIsConflict checks if the response status is 409 Conflict. It has the priority 1, and it has the top priority. Usage: On(StatusIsConflict, func(r *http.Response) error{}) -> only matches when the status code is 409

View Source
var StatusIsContinue = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusContinue
}, 1)

StatusIsContinue checks if the response status is 100 Continue. It has the priority 1, and it has the top priority. Usage: On(StatusIsContinue, func(r *http.Response) error{}) -> only matches when the status code is 100

View Source
var StatusIsCreated = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusCreated
}, 1)

StatusIsCreated checks if the response status is 201 Created. It has the priority 1, and it has the top priority. Usage: On(StatusIsCreated, func(r *http.Response) error{}) -> only matches when the status code is 201

View Source
var StatusIsEarlyHints = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusEarlyHints
}, 1)

StatusIsEarlyHints checks if the response status is 103 Early Hints. It has the priority 1, and it has the top priority. Usage: On(StatusIsEarlyHints, func(r *http.Response) error{}) -> only matches when the status code is 103

View Source
var StatusIsExpectationFailed = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusExpectationFailed
}, 1)

StatusIsExpectationFailed checks if the response status is 417 Expectation Failed. It has the priority 1, and it has the top priority. Usage: On(StatusIsExpectationFailed, func(r *http.Response) error{}) -> only matches when the status code is 417

View Source
var StatusIsFailedDependency = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusFailedDependency
}, 1)

StatusIsFailedDependency checks if the response status is 424 Failed Dependency. It has the priority 1, and it has the top priority. Usage: On(StatusIsFailedDependency, func(r *http.Response) error{}) -> only matches when the status code is 424

View Source
var StatusIsForbidden = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusForbidden
}, 1)

StatusIsForbidden checks if the response status is 403 Forbidden. It has the priority 1, and it has the top priority. Usage: On(StatusIsForbidden, func(r *http.Response) error{}) -> only matches when the status code is 403

View Source
var StatusIsFound = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusFound
}, 1)

StatusIsFound checks if the response status is 302 Found. It has the priority 1, and it has the top priority. Usage: On(StatusIsFound, func(r *http.Response) error{}) -> only matches when the status code is 302

View Source
var StatusIsGatewayTimeout = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusGatewayTimeout
}, 1)

StatusIsGatewayTimeout checks if the response status is 504 Gateway Timeout. It has the priority 1, and it has the top priority. Usage: On(StatusIsGatewayTimeout, func(r *http.Response) error{}) -> only matches when the status code is 504

View Source
var StatusIsGone = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusGone
}, 1)

StatusIsGone checks if the response status is 410 Gone. It has the priority 1, and it has the top priority. Usage: On(StatusIsGone, func(r *http.Response) error{}) -> only matches when the status code is 410

View Source
var StatusIsHTTPVersionNotSupported = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusHTTPVersionNotSupported
}, 1)

StatusIsHTTPVersionNotSupported checks if the response status is 505 HTTP Version Not Supported. It has the priority 1, and it has the top priority. Usage: On(StatusIsHTTPVersionNotSupported, func(r *http.Response) error{}) -> only matches when the status code is 505

View Source
var StatusIsIMUsed = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusIMUsed
}, 1)

StatusIsIMUsed checks if the response status is 226 IM Used. It has the priority 1, and it has the top priority. Usage: On(StatusIsIMUsed, func(r *http.Response) error{}) -> only matches when the status code is 226

View Source
var StatusIsInformational = newStatusChecker(func(statusCode int) bool {
	return statusCode < http.StatusOK
}, 3)

StatusIsInformational checks if the response status code is less than 200. It has the priority 3, and it is checked after StatusIsOneOf. Usage: On(StatusIsInformational,func(r *http.Response) error{})

View Source
var StatusIsInsufficientStorage = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusInsufficientStorage
}, 1)

StatusIsInsufficientStorage checks if the response status is 507 Insufficient Storage. It has the priority 1, and it has the top priority. Usage: On(StatusIsInsufficientStorage, func(r *http.Response) error{}) -> only matches when the status code is 507

View Source
var StatusIsInternalServerError = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusInternalServerError
}, 1)

StatusIsInternalServerError checks if the response status is 500 Internal Server Error. It has the priority 1, and it has the top priority. Usage: On(StatusIsInternalServerError, func(r *http.Response) error{}) -> only matches when the status code is 500

View Source
var StatusIsLengthRequired = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusLengthRequired
}, 1)

StatusIsLengthRequired checks if the response status is 411 Length Required. It has the priority 1, and it has the top priority. Usage: On(StatusIsLengthRequired, func(r *http.Response) error{}) -> only matches when the status code is 411

View Source
var StatusIsLocked = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusLocked
}, 1)

StatusIsLocked checks if the response status is 423 Locked. It has the priority 1, and it has the top priority. Usage: On(StatusIsLocked, func(r *http.Response) error{}) -> only matches when the status code is 423

View Source
var StatusIsLoopDetected = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusLoopDetected
}, 1)

StatusIsLoopDetected checks if the response status is 508 Loop Detected. It has the priority 1, and it has the top priority. Usage: On(StatusIsLoopDetected, func(r *http.Response) error{}) -> only matches when the status code is 508

View Source
var StatusIsMethodNotAllowed = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusMethodNotAllowed
}, 1)

StatusIsMethodNotAllowed checks if the response status is 405 Method Not Allowed. It has the priority 1, and it has the top priority. Usage: On(StatusIsMethodNotAllowed, func(r *http.Response) error{}) -> only matches when the status code is 405

View Source
var StatusIsMisdirectedRequest = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusMisdirectedRequest
}, 1)

StatusIsMisdirectedRequest checks if the response status is 421 Misdirected Request. It has the priority 1, and it has the top priority. Usage: On(StatusIsMisdirectedRequest, func(r *http.Response) error{}) -> only matches when the status code is 421

View Source
var StatusIsMovedPermanently = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusMovedPermanently
}, 1)

StatusIsMovedPermanently checks if the response status is 301 Moved Permanently. It has the priority 1, and it has the top priority. Usage: On(StatusIsMovedPermanently, func(r *http.Response) error{}) -> only matches when the status code is 301

View Source
var StatusIsMultiStatus = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusMultiStatus
}, 1)

StatusIsMultiStatus checks if the response status is 207 Multi-Status. It has the priority 1, and it has the top priority. Usage: On(StatusIsMultiStatus, func(r *http.Response) error{}) -> only matches when the status code is 207

View Source
var StatusIsMultipleChoices = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusMultipleChoices
}, 1)

StatusIsMultipleChoices checks if the response status is 300 Multiple Choices. It has the priority 1, and it has the top priority. Usage: On(StatusIsMultipleChoices, func(r *http.Response) error{}) -> only matches when the status code is 300

View Source
var StatusIsNetworkAuthenticationRequired = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNetworkAuthenticationRequired
}, 1)

StatusIsNetworkAuthenticationRequired checks if the response status is 511 Network Authentication Required. It has the priority 1, and it has the top priority. Usage: On(StatusIsNetworkAuthenticationRequired, func(r *http.Response) error{}) -> only matches when the status code is 511

View Source
var StatusIsNoContent = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNoContent
}, 1)

StatusIsNoContent checks if the response status is 204 No Content. It has the priority 1, and it has the top priority. Usage: On(StatusIsNoContent, func(r *http.Response) error{}) -> only matches when the status code is 204

View Source
var StatusIsNonAuthoritativeInfo = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNonAuthoritativeInfo
}, 1)

StatusIsNonAuthoritativeInfo checks if the response status is 203 Non-Authoritative Information. It has the priority 1, and it has the top priority. Usage: On(StatusIsNonAuthoritativeInfo, func(r *http.Response) error{}) -> only matches when the status code is 203

View Source
var StatusIsNotAcceptable = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNotAcceptable
}, 1)

StatusIsNotAcceptable checks if the response status is 406 Not Acceptable. It has the priority 1, and it has the top priority. Usage: On(StatusIsNotAcceptable, func(r *http.Response) error{}) -> only matches when the status code is 406

View Source
var StatusIsNotExtended = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNotExtended
}, 1)

StatusIsNotExtended checks if the response status is 510 Not Extended. It has the priority 1, and it has the top priority. Usage: On(StatusIsNotExtended, func(r *http.Response) error{}) -> only matches when the status code is 510

View Source
var StatusIsNotFound = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNotFound
}, 1)

StatusIsNotFound checks if the response status is 404 Not Found. It has the priority 1, and it has the top priority. Usage: On(StatusIsNotFound, func(r *http.Response) error{}) -> only matches when the status code is 404

View Source
var StatusIsNotImplemented = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNotImplemented
}, 1)

StatusIsNotImplemented checks if the response status is 501 Not Implemented. It has the priority 1, and it has the top priority. Usage: On(StatusIsNotImplemented, func(r *http.Response) error{}) -> only matches when the status code is 501

View Source
var StatusIsNotModified = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusNotModified
}, 1)

StatusIsNotModified checks if the response status is 304 Not Modified. It has the priority 1, and it has the top priority. Usage: On(StatusIsNotModified, func(r *http.Response) error{}) -> only matches when the status code is 304

View Source
var StatusIsOk = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusOK
}, 1)

StatusIsOk checks if the response status is 200 OK. It has the priority 1, and it has the top priority. Usage: On(StatusIsOk, func(r *http.Response) error{}) -> only matches when the status code is 200

View Source
var StatusIsPartialContent = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusPartialContent
}, 1)

StatusIsPartialContent checks if the response status is 206 Partial Content. It has the priority 1, and it has the top priority. Usage: On(StatusIsPartialContent, func(r *http.Response) error{}) -> only matches when the status code is 206

View Source
var StatusIsPaymentRequired = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusPaymentRequired
}, 1)

StatusIsPaymentRequired checks if the response status is 402 Payment Required. It has the priority 1, and it has the top priority. Usage: On(StatusIsPaymentRequired, func(r *http.Response) error{}) -> only matches when the status code is 402

View Source
var StatusIsPermanentRedirect = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusPermanentRedirect
}, 1)

StatusIsPermanentRedirect checks if the response status is 308 Permanent Redirect. It has the priority 1, and it has the top priority. Usage: On(StatusIsPermanentRedirect, func(r *http.Response) error{}) -> only matches when the status code is 308

View Source
var StatusIsPreconditionFailed = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusPreconditionFailed
}, 1)

StatusIsPreconditionFailed checks if the response status is 412 Precondition Failed. It has the priority 1, and it has the top priority. Usage: On(StatusIsPreconditionFailed, func(r *http.Response) error{}) -> only matches when the status code is 412

View Source
var StatusIsPreconditionRequired = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusPreconditionRequired
}, 1)

StatusIsPreconditionRequired checks if the response status is 428 Precondition Required. It has the priority 1, and it has the top priority. Usage: On(StatusIsPreconditionRequired, func(r *http.Response) error{}) -> only matches when the status code is 428

View Source
var StatusIsProcessing = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusProcessing
}, 1)

StatusIsProcessing checks if the response status is 102 Processing. It has the priority 1, and it has the top priority. Usage: On(StatusIsProcessing, func(r *http.Response) error{}) -> only matches when the status code is 102

View Source
var StatusIsProxyAuthRequired = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusProxyAuthRequired
}, 1)

StatusIsProxyAuthRequired checks if the response status is 407 Proxy Authentication Required. It has the priority 1, and it has the top priority. Usage: On(StatusIsProxyAuthRequired, func(r *http.Response) error{}) -> only matches when the status code is 407

View Source
var StatusIsRedirection = newStatusChecker(func(statusCode int) bool {
	return statusCode >= http.StatusMultipleChoices && statusCode < http.StatusBadRequest
}, 3)

StatusIsRedirection checks if the response status code is between [300,400). It has the priority 3, and it is checked after StatusIsOneOf. Usage: On(StatusIsRedirection,func(r *http.Response) error{})

View Source
var StatusIsRequestEntityTooLarge = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusRequestEntityTooLarge
}, 1)

StatusIsRequestEntityTooLarge checks if the response status is 413 Request Entity Too Large. It has the priority 1, and it has the top priority. Usage: On(StatusIsRequestEntityTooLarge, func(r *http.Response) error{}) -> only matches when the status code is 413

View Source
var StatusIsRequestHeaderFieldsTooLarge = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusRequestHeaderFieldsTooLarge
}, 1)

StatusIsRequestHeaderFieldsTooLarge checks if the response status is 431 Request Header Fields Too Large. It has the priority 1, and it has the top priority. Usage: On(StatusIsRequestHeaderFieldsTooLarge, func(r *http.Response) error{}) -> only matches when the status code is 431

View Source
var StatusIsRequestTimeout = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusRequestTimeout
}, 1)

StatusIsRequestTimeout checks if the response status is 408 Request Timeout. It has the priority 1, and it has the top priority. Usage: On(StatusIsRequestTimeout, func(r *http.Response) error{}) -> only matches when the status code is 408

View Source
var StatusIsRequestURITooLong = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusRequestURITooLong
}, 1)

StatusIsRequestURITooLong checks if the response status is 414 Request URI Too Long. It has the priority 1, and it has the top priority. Usage: On(StatusIsRequestURITooLong, func(r *http.Response) error{}) -> only matches when the status code is 414

View Source
var StatusIsRequestedRangeNotSatisfiable = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusRequestedRangeNotSatisfiable
}, 1)

StatusIsRequestedRangeNotSatisfiable checks if the response status is 416 Requested Range Not Satisfiable. It has the priority 1, and it has the top priority. Usage: On(StatusIsRequestedRangeNotSatisfiable, func(r *http.Response) error{}) -> only matches when the status code is 416

View Source
var StatusIsResetContent = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusResetContent
}, 1)

StatusIsResetContent checks if the response status is 205 Reset Content. It has the priority 1, and it has the top priority. Usage: On(StatusIsResetContent, func(r *http.Response) error{}) -> only matches when the status code is 205

View Source
var StatusIsSeeOther = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusSeeOther
}, 1)

StatusIsSeeOther checks if the response status is 303 See Other. It has the priority 1, and it has the top priority. Usage: On(StatusIsSeeOther, func(r *http.Response) error{}) -> only matches when the status code is 303

View Source
var StatusIsServerError = newStatusChecker(func(statusCode int) bool {
	return statusCode >= 500
}, 3)

StatusIsServerError checks if the response status is greater or equal than 500. It has the priority 3, and it is checked after StatusIsOneOf. Usage: On(StatusIsServerError,func(r *http.Response) error{})

View Source
var StatusIsServiceUnavailable = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusServiceUnavailable
}, 1)

StatusIsServiceUnavailable checks if the response status is 503 Service Unavailable. It has the priority 1, and it has the top priority. Usage: On(StatusIsServiceUnavailable, func(r *http.Response) error{}) -> only matches when the status code is 503

View Source
var StatusIsSuccess = newStatusChecker(func(statusCode int) bool {
	return statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices
}, 3)

StatusIsSuccess checks if the response status code is between [200,300). It has the priority 3, and it is checked after StatusIsOneOf. Usage: On(StatusIsSuccess,func(r *http.Response) error{})

View Source
var StatusIsSwitchingProtocols = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusSwitchingProtocols
}, 1)

StatusIsSwitchingProtocols checks if the response status is 101 Switching Protocols. It has the priority 1, and it has the top priority. Usage: On(StatusIsSwitchingProtocols, func(r *http.Response) error{}) -> only matches when the status code is 101

View Source
var StatusIsTeapot = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusTeapot
}, 1)

StatusIsTeapot checks if the response status is 418 I'm a teapot. It has the priority 1, and it has the top priority. Usage: On(StatusIsTeapot, func(r *http.Response) error{}) -> only matches when the status code is 418

View Source
var StatusIsTemporaryRedirect = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusTemporaryRedirect
}, 1)

StatusIsTemporaryRedirect checks if the response status is 307 Temporary Redirect. It has the priority 1, and it has the top priority. Usage: On(StatusIsTemporaryRedirect, func(r *http.Response) error{}) -> only matches when the status code is 307

View Source
var StatusIsTooEarly = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusTooEarly
}, 1)

StatusIsTooEarly checks if the response status is 425 Too Early. It has the priority 1, and it has the top priority. Usage: On(StatusIsTooEarly, func(r *http.Response) error{}) -> only matches when the status code is 425

View Source
var StatusIsTooManyRequests = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusTooManyRequests
}, 1)

StatusIsTooManyRequests checks if the response status is 429 Too Many Requests. It has the priority 1, and it has the top priority. Usage: On(StatusIsTooManyRequests, func(r *http.Response) error{}) -> only matches when the status code is 429

View Source
var StatusIsUnauthorized = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusUnauthorized
}, 1)

StatusIsUnauthorized checks if the response status is 401 Unauthorized. It has the priority 1, and it has the top priority. Usage: On(StatusIsUnauthorized, func(r *http.Response) error{}) -> only matches when the status code is 401

View Source
var StatusIsUnavailableForLegalReasons = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusUnavailableForLegalReasons
}, 1)

StatusIsUnavailableForLegalReasons checks if the response status is 451 Unavailable For Legal Reasons. It has the priority 1, and it has the top priority. Usage: On(StatusIsUnavailableForLegalReasons, func(r *http.Response) error{}) -> only matches when the status code is 451

View Source
var StatusIsUnprocessableEntity = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusUnprocessableEntity
}, 1)

StatusIsUnprocessableEntity checks if the response status is 422 Unprocessable Entity. It has the priority 1, and it has the top priority. Usage: On(StatusIsUnprocessableEntity, func(r *http.Response) error{}) -> only matches when the status code is 422

View Source
var StatusIsUnsupportedMediaType = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusUnsupportedMediaType
}, 1)

StatusIsUnsupportedMediaType checks if the response status is 415 Unsupported Media Type. It has the priority 1, and it has the top priority. Usage: On(StatusIsUnsupportedMediaType, func(r *http.Response) error{}) -> only matches when the status code is 415

View Source
var StatusIsUpgradeRequired = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusUpgradeRequired
}, 1)

StatusIsUpgradeRequired checks if the response status is 426 Upgrade Required. It has the priority 1, and it has the top priority. Usage: On(StatusIsUpgradeRequired, func(r *http.Response) error{}) -> only matches when the status code is 426

View Source
var StatusIsUseProxy = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusUseProxy
}, 1)

StatusIsUseProxy checks if the response status is 305 Use Proxy. It has the priority 1, and it has the top priority. Usage: On(StatusIsUseProxy, func(r *http.Response) error{}) -> only matches when the status code is 305

View Source
var StatusIsVariantAlsoNegotiates = newStatusChecker(func(statusCode int) bool {
	return statusCode == http.StatusVariantAlsoNegotiates
}, 1)

StatusIsVariantAlsoNegotiates checks if the response status is 506 Variant Also Negotiates. It has the priority 1, and it has the top priority. Usage: On(StatusIsVariantAlsoNegotiates, func(r *http.Response) error{}) -> only matches when the status code is 506

Functions

func ContextWithLogger added in v1.2.0

func ContextWithLogger(ctx context.Context, logger Logger) context.Context

func DefaultClient added in v1.2.0

func DefaultClient() *http.Client

DefaultClient returns a new http.Client with similar default values to http.Client, but with a non-shared Transport, idle connections disabled, and keepalives disabled.

func DefaultPooledClient added in v1.2.0

func DefaultPooledClient() *http.Client

DefaultPooledClient returns a new http.Client with similar default values to http.Client, but with a shared Transport. Do not use this function for transient clients as it can leak file descriptors over time. Only use this for clients that will be re-used for the same host(s).

func DefaultPooledTransport added in v1.2.0

func DefaultPooledTransport() *http.Transport

DefaultPooledTransport returns a new http.Transport with similar default values to http.DefaultTransport. Do not use this for transient transports as it can leak file descriptors over time. Only use this for transports that will be re-used for the same host(s).

func DefaultTransport added in v1.2.0

func DefaultTransport() *http.Transport

DefaultTransport returns a new http.Transport with similar default values to http.DefaultTransport, but with idle connections and keepalives disabled.

func DrainBodyAndClose

func DrainBodyAndClose(response *http.Response) error

func ExtractRequestIDFromContext added in v1.3.0

func ExtractRequestIDFromContext(ctx context.Context) *string

func ExtractRetryAttemptFromContext added in v1.4.0

func ExtractRetryAttemptFromContext(ctx context.Context) int

ExtractRetryAttemptFromContext returns the current retry attempt number from the context. Returns 0 if not in a retry context (i.e., first attempt or no retry middleware).

func GetBasicAuthHeaderValue added in v1.3.0

func GetBasicAuthHeaderValue(username, password string) string

func GetTokenHeaderValue added in v1.3.0

func GetTokenHeaderValue(token string) string

func ThenDoNothing added in v1.3.0

func ThenDoNothing(_ *http.Response) error

ThenDoNothing returns nil error Usage: On(StatusAny, ThenDoNothing)

func ThenReturnDefaultError added in v1.3.0

func ThenReturnDefaultError(r *http.Response) error

ThenReturnDefaultError returns an error that contains the request method, requests URL and the status code Usage: On(StatusAny, ThenReturnDefaultError)

Types

type Client

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

func New

func New() *Client

func (*Client) AcceptJson

func (c *Client) AcceptJson() *Client

func (*Client) AuthBasic

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

func (*Client) AuthToken

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

func (*Client) BasePath

func (c *Client) BasePath(basePath string) *Client

func (*Client) Close added in v1.0.0

func (c *Client) Close()

Close closes all idle connections and cleans up resources. Call this when you're done using the client. After calling Close, the client should not be reused. It also cancels all the requests done via Get, Post, Put, Head, Patch, Delete, in short, methods without context.

func (*Client) ContentType

func (c *Client) ContentType(contentType string) *Client

func (*Client) ContentTypeFormUrlEncoded

func (c *Client) ContentTypeFormUrlEncoded() *Client

func (*Client) ContentTypeHtml

func (c *Client) ContentTypeHtml() *Client

func (*Client) ContentTypeJson

func (c *Client) ContentTypeJson() *Client

func (*Client) ContentTypeText

func (c *Client) ContentTypeText() *Client

func (*Client) ContentTypeXml

func (c *Client) ContentTypeXml() *Client

func (*Client) Delete

func (c *Client) Delete(url string, body Requester) *Req

func (*Client) DeleteCtx

func (c *Client) DeleteCtx(ctx context.Context, url string, body Requester) *Req

func (*Client) DisableHTTP2 added in v1.0.0

func (c *Client) DisableHTTP2() *Client

func (*Client) DisableRedirects

func (c *Client) DisableRedirects() *Client

func (*Client) DisableTLSVerification added in v1.0.0

func (c *Client) DisableTLSVerification() *Client

func (*Client) EnableCookies

func (c *Client) EnableCookies() *Client

func (*Client) FollowRedirects

func (c *Client) FollowRedirects(maxRedirect int) *Client

FollowRedirects sets how many times it should follow the redirects. Value zero disables the following.

func (*Client) Get

func (c *Client) Get(url string) *Req

func (*Client) GetCtx

func (c *Client) GetCtx(ctx context.Context, url string) *Req

func (*Client) Head added in v1.0.0

func (c *Client) Head(url string) *Req

func (*Client) HeadCtx added in v1.0.0

func (c *Client) HeadCtx(ctx context.Context, url string) *Req

func (*Client) Header

func (c *Client) Header(key, val string) *Client

func (*Client) Patch

func (c *Client) Patch(url string, body Requester) *Req

func (*Client) PatchCtx

func (c *Client) PatchCtx(ctx context.Context, url string, body Requester) *Req

func (*Client) Post

func (c *Client) Post(url string, body Requester) *Req

func (*Client) PostCtx

func (c *Client) PostCtx(ctx context.Context, url string, body Requester) *Req

func (*Client) Put

func (c *Client) Put(url string, body Requester) *Req

func (*Client) PutCtx

func (c *Client) PutCtx(ctx context.Context, url string, body Requester) *Req

func (*Client) QueryBool

func (c *Client) QueryBool(name string, v bool) *Client

func (*Client) QueryBoolPtr

func (c *Client) QueryBoolPtr(name string, v *bool) *Client

func (*Client) QueryFloat32

func (c *Client) QueryFloat32(name string, v float32) *Client

func (*Client) QueryFloat32Ptr

func (c *Client) QueryFloat32Ptr(name string, v *float32) *Client

func (*Client) QueryFloat64

func (c *Client) QueryFloat64(name string, v float64) *Client

func (*Client) QueryFloat64Ptr

func (c *Client) QueryFloat64Ptr(name string, v *float64) *Client

func (*Client) QueryInt

func (c *Client) QueryInt(name string, v int) *Client

func (*Client) QueryInt8

func (c *Client) QueryInt8(name string, v int8) *Client

func (*Client) QueryInt8Ptr

func (c *Client) QueryInt8Ptr(name string, v *int8) *Client

func (*Client) QueryInt16

func (c *Client) QueryInt16(name string, v int16) *Client

func (*Client) QueryInt16Ptr

func (c *Client) QueryInt16Ptr(name string, v *int16) *Client

func (*Client) QueryInt32

func (c *Client) QueryInt32(name string, v int32) *Client

func (*Client) QueryInt32Ptr

func (c *Client) QueryInt32Ptr(name string, v *int32) *Client

func (*Client) QueryInt64

func (c *Client) QueryInt64(name string, v int64) *Client

func (*Client) QueryInt64Ptr

func (c *Client) QueryInt64Ptr(name string, v *int64) *Client

func (*Client) QueryIntPtr

func (c *Client) QueryIntPtr(name string, v *int) *Client

func (*Client) QueryString

func (c *Client) QueryString(name string, v string) *Client

func (*Client) QueryStringPtr

func (c *Client) QueryStringPtr(name string, v *string) *Client

func (*Client) QueryUint

func (c *Client) QueryUint(name string, v uint) *Client

func (*Client) QueryUint8

func (c *Client) QueryUint8(name string, v uint8) *Client

func (*Client) QueryUint8Ptr

func (c *Client) QueryUint8Ptr(name string, v *uint8) *Client

func (*Client) QueryUint16

func (c *Client) QueryUint16(name string, v uint16) *Client

func (*Client) QueryUint16Ptr

func (c *Client) QueryUint16Ptr(name string, v *uint16) *Client

func (*Client) QueryUint32

func (c *Client) QueryUint32(name string, v uint32) *Client

func (*Client) QueryUint32Ptr

func (c *Client) QueryUint32Ptr(name string, v *uint32) *Client

func (*Client) QueryUint64

func (c *Client) QueryUint64(name string, v uint64) *Client

func (*Client) QueryUint64Ptr

func (c *Client) QueryUint64Ptr(name string, v *uint64) *Client

func (*Client) QueryUintPtr

func (c *Client) QueryUintPtr(name string, v *uint) *Client

func (*Client) TimeOutIn

func (c *Client) TimeOutIn(duration time.Duration) *Client

func (*Client) TlsConfig

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

func (*Client) ToStandardClient added in v1.0.0

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

func (*Client) Use added in v1.3.0

func (c *Client) Use(mws ...Middleware) *Client

func (*Client) UserAgent

func (c *Client) UserAgent(userAgent string) *Client

type CustomRetryChecker added in v1.2.0

type CustomRetryChecker func(resp *http.Response, err error) bool

type DefaultError added in v1.2.0

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

func (*DefaultError) Error added in v1.2.0

func (d *DefaultError) Error() string

type ErrorHandler

type ErrorHandler func(serverError error) error

type LogLevel added in v1.1.0

type LogLevel int
const (
	LogLevelError LogLevel = iota
	LogLevelWarn
	LogLevelInfo
	LogLevelDebug
)

type Logger added in v1.1.0

type Logger interface {
	Error(ctx context.Context, err error, msg string, fields ...any)
	Warn(ctx context.Context, msg string, fields ...any)
	Info(ctx context.Context, msg string, fields ...any)
	Debug(ctx context.Context, msg string, fields ...any)
}

func ExtractLoggerFromContext added in v1.3.0

func ExtractLoggerFromContext(ctx context.Context) Logger

func NewInpuLoggerFromSlog added in v1.3.0

func NewInpuLoggerFromSlog(level LogLevel) Logger

type Middleware

type Middleware interface {
	ID() string
	Priority() int
	Apply(next http.RoundTripper) http.RoundTripper
}

func ErrorHandlerMiddleware

func ErrorHandlerMiddleware(handler ErrorHandler) Middleware

ErrorHandlerMiddleware handles server errors

func LoggingMiddleware

func LoggingMiddleware(verbose, disabled bool) Middleware

LoggingMiddleware creates a logging middleware

func RequestIDMiddleware

func RequestIDMiddleware() Middleware

RequestIDMiddleware add HeaderXRequestID to every request

func RequestModifierMiddleware

func RequestModifierMiddleware(modifier RequestModifier, middlewareID string, priority int) Middleware

RequestModifierMiddleware creates a middleware that allows request to be modified

func ResponseModifierMiddleware

func ResponseModifierMiddleware(modifier ResponseModifier, middlewareID string, priority int) Middleware

ResponseModifierMiddleware creates a middleware that allows request to be modified

func RetryMiddleware

func RetryMiddleware(maxRetries int) Middleware

RetryMiddleware creates a retry middleware with default config

func RetryMiddlewareWithConfig

func RetryMiddlewareWithConfig(config RetryConfig) Middleware

RetryMiddlewareWithConfig creates a retry middleware with custom config

type Req

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

func Delete

func Delete(url string, body Requester) *Req

func DeleteCtx

func DeleteCtx(ctx context.Context, url string, body Requester) *Req

func Get

func Get(url string) *Req

func GetCtx

func GetCtx(ctx context.Context, url string) *Req
func Head(url string) *Req

func HeadCtx added in v1.0.0

func HeadCtx(ctx context.Context, url string) *Req

func Patch

func Patch(url string, body Requester) *Req

func PatchCtx

func PatchCtx(ctx context.Context, url string, body Requester) *Req

func Post

func Post(url string, body Requester) *Req

func PostCtx

func PostCtx(ctx context.Context, url string, body Requester) *Req

func Put

func Put(url string, body Requester) *Req

func PutCtx

func PutCtx(ctx context.Context, url string, body Requester) *Req

func (*Req) AcceptJson

func (r *Req) AcceptJson() *Req

func (*Req) AuthBasic

func (r *Req) AuthBasic(username, password string) *Req

func (*Req) AuthToken

func (r *Req) AuthToken(token string) *Req

func (*Req) ContentType

func (r *Req) ContentType(contentType string) *Req

func (*Req) ContentTypeFormUrlEncoded

func (r *Req) ContentTypeFormUrlEncoded() *Req

func (*Req) ContentTypeHtml

func (r *Req) ContentTypeHtml() *Req

func (*Req) ContentTypeJson

func (r *Req) ContentTypeJson() *Req

func (*Req) ContentTypeText

func (r *Req) ContentTypeText() *Req

func (*Req) ContentTypeXml

func (r *Req) ContentTypeXml() *Req

func (*Req) Header

func (r *Req) Header(key, val string) *Req

func (*Req) On added in v1.4.0

func (r *Req) On(statusMatcher StatusMatcher, responseHandler ResponseHandler) *Req

On adds status matcher and response handler configurations. In case a status is matched by status matcher, its response handler is executed. However, status matchers have priorities. The less priority is the higher precedence on the matching. Current status matcher priorities are: StatusIs -> 1 StatusIsOneOf -> 2 StatusIsInformational, StatusIsSuccess, StatusIsRedirection, StatusIsClientError, StatusIsServerError -> 3 StatusAnyExcept -> 8 StatusAnyExceptOneOf -> 9 StatusAny -> 10 Based on the response only one reply is executed. For example:

On(StatusIs(http.StatusOK), ThenReturnError(errors.New("something happened"))). // first one On(StatusIsSuccess, ThenReturnError(errors.New("something happened again"))). // second one On(StatusAny, ThenReturnError(errors.New("something happened again and again"))) // third one

It will execute the first response handler if the status code is 200 and return errors.New("something happened") It will execute the second response handler if the status code is 201 and return errors.New("something happened again") It will execute the third response handler if the status code is 500 or any other status code which is not success in this example and return errors.New("something happened again and again") Multiple same matcher on the same priority can be added but only first one in the addition order will be executed. For example:

On(StatusIs(http.StatusOK), ThenReturnError(errors.New("something happened"))). // first one On(StatusIs(http.StatusOK), ThenReturnError(errors.New("something happened again"))) // second one

It will return errors.New("something happened")

func (*Req) OnAccepted added in v1.4.0

func (r *Req) OnAccepted(responseHandler ResponseHandler) *Req

OnAccepted is a shorthand for On(StatusIsAccepted, responseHandler). It matches status code 202.

func (*Req) OnAlreadyReported added in v1.4.0

func (r *Req) OnAlreadyReported(responseHandler ResponseHandler) *Req

OnAlreadyReported is a shorthand for On(StatusIsAlreadyReported, responseHandler). It matches status code 208.

func (*Req) OnAny added in v1.4.0

func (r *Req) OnAny(responseHandler ResponseHandler) *Req

OnAny is a shorthand for On(StatusAny, responseHandler). It matches any status code. Useful as a fallback. Usage:

OnOk(ThenUnmarshalJsonTo(&items)).
OnAny(ThenReturnDefaultError).
Send()

func (*Req) OnAnyExcept added in v1.4.0

func (r *Req) OnAnyExcept(statusCode int, responseHandler ResponseHandler) *Req

OnAnyExcept is a shorthand for On(StatusAnyExcept(statusCode), responseHandler). It matches any status code except the one provided. Usage:

OnAnyExcept(http.StatusOK, ThenReturnDefaultError).
Send()

func (*Req) OnAnyExceptOneOf added in v1.4.0

func (r *Req) OnAnyExceptOneOf(responseHandler ResponseHandler, statusCodes ...int) *Req

OnAnyExceptOneOf is a shorthand for On(StatusAnyExceptOneOf(statusCodes...), responseHandler). It matches any status code except those provided. Usage:

OnAnyExceptOneOf(ThenReturnDefaultError, http.StatusOK, http.StatusCreated).
Send()

func (*Req) OnBadGateway added in v1.4.0

func (r *Req) OnBadGateway(responseHandler ResponseHandler) *Req

OnBadGateway is a shorthand for On(StatusIsBadGateway, responseHandler). It matches status code 502.

func (*Req) OnBadRequest added in v1.4.0

func (r *Req) OnBadRequest(responseHandler ResponseHandler) *Req

OnBadRequest is a shorthand for On(StatusIsBadRequest, responseHandler). It matches status code 400.

func (*Req) OnClientError added in v1.4.0

func (r *Req) OnClientError(responseHandler ResponseHandler) *Req

OnClientError is a shorthand for On(StatusIsClientError, responseHandler). It matches any status code in the range [400, 500).

func (*Req) OnConflict added in v1.4.0

func (r *Req) OnConflict(responseHandler ResponseHandler) *Req

OnConflict is a shorthand for On(StatusIsConflict, responseHandler). It matches status code 409.

func (*Req) OnContinue added in v1.4.0

func (r *Req) OnContinue(responseHandler ResponseHandler) *Req

OnContinue is a shorthand for On(StatusIsContinue, responseHandler). It matches status code 100.

func (*Req) OnCreated added in v1.4.0

func (r *Req) OnCreated(responseHandler ResponseHandler) *Req

OnCreated is a shorthand for On(StatusIsCreated, responseHandler). It matches status code 201.

func (*Req) OnEarlyHints added in v1.4.0

func (r *Req) OnEarlyHints(responseHandler ResponseHandler) *Req

OnEarlyHints is a shorthand for On(StatusIsEarlyHints, responseHandler). It matches status code 103.

func (*Req) OnExpectationFailed added in v1.4.0

func (r *Req) OnExpectationFailed(responseHandler ResponseHandler) *Req

OnExpectationFailed is a shorthand for On(StatusIsExpectationFailed, responseHandler). It matches status code 417.

func (*Req) OnFailedDependency added in v1.4.0

func (r *Req) OnFailedDependency(responseHandler ResponseHandler) *Req

OnFailedDependency is a shorthand for On(StatusIsFailedDependency, responseHandler). It matches status code 424.

func (*Req) OnForbidden added in v1.4.0

func (r *Req) OnForbidden(responseHandler ResponseHandler) *Req

OnForbidden is a shorthand for On(StatusIsForbidden, responseHandler). It matches status code 403.

func (*Req) OnFound added in v1.4.0

func (r *Req) OnFound(responseHandler ResponseHandler) *Req

OnFound is a shorthand for On(StatusIsFound, responseHandler). It matches status code 302.

func (*Req) OnGatewayTimeout added in v1.4.0

func (r *Req) OnGatewayTimeout(responseHandler ResponseHandler) *Req

OnGatewayTimeout is a shorthand for On(StatusIsGatewayTimeout, responseHandler). It matches status code 504.

func (*Req) OnGone added in v1.4.0

func (r *Req) OnGone(responseHandler ResponseHandler) *Req

OnGone is a shorthand for On(StatusIsGone, responseHandler). It matches status code 410.

func (*Req) OnHTTPVersionNotSupported added in v1.4.0

func (r *Req) OnHTTPVersionNotSupported(responseHandler ResponseHandler) *Req

OnHTTPVersionNotSupported is a shorthand for On(StatusIsHTTPVersionNotSupported, responseHandler). It matches status code 505.

func (*Req) OnIMUsed added in v1.4.0

func (r *Req) OnIMUsed(responseHandler ResponseHandler) *Req

OnIMUsed is a shorthand for On(StatusIsIMUsed, responseHandler). It matches status code 226.

func (*Req) OnInformational added in v1.4.0

func (r *Req) OnInformational(responseHandler ResponseHandler) *Req

OnInformational is a shorthand for On(StatusIsInformational, responseHandler). It matches any status code less than 200.

func (*Req) OnInsufficientStorage added in v1.4.0

func (r *Req) OnInsufficientStorage(responseHandler ResponseHandler) *Req

OnInsufficientStorage is a shorthand for On(StatusIsInsufficientStorage, responseHandler). It matches status code 507.

func (*Req) OnInternalServerError added in v1.4.0

func (r *Req) OnInternalServerError(responseHandler ResponseHandler) *Req

OnInternalServerError is a shorthand for On(StatusIsInternalServerError, responseHandler). It matches status code 500.

func (*Req) OnLengthRequired added in v1.4.0

func (r *Req) OnLengthRequired(responseHandler ResponseHandler) *Req

OnLengthRequired is a shorthand for On(StatusIsLengthRequired, responseHandler). It matches status code 411.

func (*Req) OnLocked added in v1.4.0

func (r *Req) OnLocked(responseHandler ResponseHandler) *Req

OnLocked is a shorthand for On(StatusIsLocked, responseHandler). It matches status code 423.

func (*Req) OnLoopDetected added in v1.4.0

func (r *Req) OnLoopDetected(responseHandler ResponseHandler) *Req

OnLoopDetected is a shorthand for On(StatusIsLoopDetected, responseHandler). It matches status code 508.

func (*Req) OnMethodNotAllowed added in v1.4.0

func (r *Req) OnMethodNotAllowed(responseHandler ResponseHandler) *Req

OnMethodNotAllowed is a shorthand for On(StatusIsMethodNotAllowed, responseHandler). It matches status code 405.

func (*Req) OnMisdirectedRequest added in v1.4.0

func (r *Req) OnMisdirectedRequest(responseHandler ResponseHandler) *Req

OnMisdirectedRequest is a shorthand for On(StatusIsMisdirectedRequest, responseHandler). It matches status code 421.

func (*Req) OnMovedPermanently added in v1.4.0

func (r *Req) OnMovedPermanently(responseHandler ResponseHandler) *Req

OnMovedPermanently is a shorthand for On(StatusIsMovedPermanently, responseHandler). It matches status code 301.

func (*Req) OnMultiStatus added in v1.4.0

func (r *Req) OnMultiStatus(responseHandler ResponseHandler) *Req

OnMultiStatus is a shorthand for On(StatusIsMultiStatus, responseHandler). It matches status code 207.

func (*Req) OnMultipleChoices added in v1.4.0

func (r *Req) OnMultipleChoices(responseHandler ResponseHandler) *Req

OnMultipleChoices is a shorthand for On(StatusIsMultipleChoices, responseHandler). It matches status code 300.

func (*Req) OnNetworkAuthenticationRequired added in v1.4.0

func (r *Req) OnNetworkAuthenticationRequired(responseHandler ResponseHandler) *Req

OnNetworkAuthenticationRequired is a shorthand for On(StatusIsNetworkAuthenticationRequired, responseHandler). It matches status code 511.

func (*Req) OnNoContent added in v1.4.0

func (r *Req) OnNoContent(responseHandler ResponseHandler) *Req

OnNoContent is a shorthand for On(StatusIsNoContent, responseHandler). It matches status code 204.

func (*Req) OnNonAuthoritativeInfo added in v1.4.0

func (r *Req) OnNonAuthoritativeInfo(responseHandler ResponseHandler) *Req

OnNonAuthoritativeInfo is a shorthand for On(StatusIsNonAuthoritativeInfo, responseHandler). It matches status code 203.

func (*Req) OnNotAcceptable added in v1.4.0

func (r *Req) OnNotAcceptable(responseHandler ResponseHandler) *Req

OnNotAcceptable is a shorthand for On(StatusIsNotAcceptable, responseHandler). It matches status code 406.

func (*Req) OnNotExtended added in v1.4.0

func (r *Req) OnNotExtended(responseHandler ResponseHandler) *Req

OnNotExtended is a shorthand for On(StatusIsNotExtended, responseHandler). It matches status code 510.

func (*Req) OnNotFound added in v1.4.0

func (r *Req) OnNotFound(responseHandler ResponseHandler) *Req

OnNotFound is a shorthand for On(StatusIsNotFound, responseHandler). It matches status code 404.

func (*Req) OnNotImplemented added in v1.4.0

func (r *Req) OnNotImplemented(responseHandler ResponseHandler) *Req

OnNotImplemented is a shorthand for On(StatusIsNotImplemented, responseHandler). It matches status code 501.

func (*Req) OnNotModified added in v1.4.0

func (r *Req) OnNotModified(responseHandler ResponseHandler) *Req

OnNotModified is a shorthand for On(StatusIsNotModified, responseHandler). It matches status code 304.

func (*Req) OnOk added in v1.4.0

func (r *Req) OnOk(responseHandler ResponseHandler) *Req

OnOk is a shorthand for On(StatusIsOk, responseHandler). It matches status code 200. Usage:

OnOk(ThenUnmarshalJsonTo(&items)).
OnAny(ThenReturnDefaultError).
Send()

func (*Req) OnOneOf added in v1.4.0

func (r *Req) OnOneOf(responseHandler ResponseHandler, statusCodes ...int) *Req

OnOneOf is a shorthand for On(StatusIsOneOf(statusCodes...), responseHandler). It matches any of the provided status codes. Usage:

OnOneOf(ThenUnmarshalJsonTo(&items), http.StatusOK, http.StatusCreated).
Send()

func (*Req) OnPartialContent added in v1.4.0

func (r *Req) OnPartialContent(responseHandler ResponseHandler) *Req

OnPartialContent is a shorthand for On(StatusIsPartialContent, responseHandler). It matches status code 206.

func (*Req) OnPaymentRequired added in v1.4.0

func (r *Req) OnPaymentRequired(responseHandler ResponseHandler) *Req

OnPaymentRequired is a shorthand for On(StatusIsPaymentRequired, responseHandler). It matches status code 402.

func (*Req) OnPermanentRedirect added in v1.4.0

func (r *Req) OnPermanentRedirect(responseHandler ResponseHandler) *Req

OnPermanentRedirect is a shorthand for On(StatusIsPermanentRedirect, responseHandler). It matches status code 308.

func (*Req) OnPreconditionFailed added in v1.4.0

func (r *Req) OnPreconditionFailed(responseHandler ResponseHandler) *Req

OnPreconditionFailed is a shorthand for On(StatusIsPreconditionFailed, responseHandler). It matches status code 412.

func (*Req) OnPreconditionRequired added in v1.4.0

func (r *Req) OnPreconditionRequired(responseHandler ResponseHandler) *Req

OnPreconditionRequired is a shorthand for On(StatusIsPreconditionRequired, responseHandler). It matches status code 428.

func (*Req) OnProcessing added in v1.4.0

func (r *Req) OnProcessing(responseHandler ResponseHandler) *Req

OnProcessing is a shorthand for On(StatusIsProcessing, responseHandler). It matches status code 102.

func (*Req) OnProxyAuthRequired added in v1.4.0

func (r *Req) OnProxyAuthRequired(responseHandler ResponseHandler) *Req

OnProxyAuthRequired is a shorthand for On(StatusIsProxyAuthRequired, responseHandler). It matches status code 407.

func (*Req) OnRedirection added in v1.4.0

func (r *Req) OnRedirection(responseHandler ResponseHandler) *Req

OnRedirection is a shorthand for On(StatusIsRedirection, responseHandler). It matches any status code in the range [300, 400).

func (*Req) OnRequestEntityTooLarge added in v1.4.0

func (r *Req) OnRequestEntityTooLarge(responseHandler ResponseHandler) *Req

OnRequestEntityTooLarge is a shorthand for On(StatusIsRequestEntityTooLarge, responseHandler). It matches status code 413.

func (*Req) OnRequestHeaderFieldsTooLarge added in v1.4.0

func (r *Req) OnRequestHeaderFieldsTooLarge(responseHandler ResponseHandler) *Req

OnRequestHeaderFieldsTooLarge is a shorthand for On(StatusIsRequestHeaderFieldsTooLarge, responseHandler). It matches status code 431.

func (*Req) OnRequestTimeout added in v1.4.0

func (r *Req) OnRequestTimeout(responseHandler ResponseHandler) *Req

OnRequestTimeout is a shorthand for On(StatusIsRequestTimeout, responseHandler). It matches status code 408.

func (*Req) OnRequestURITooLong added in v1.4.0

func (r *Req) OnRequestURITooLong(responseHandler ResponseHandler) *Req

OnRequestURITooLong is a shorthand for On(StatusIsRequestURITooLong, responseHandler). It matches status code 414.

func (*Req) OnRequestedRangeNotSatisfiable added in v1.4.0

func (r *Req) OnRequestedRangeNotSatisfiable(responseHandler ResponseHandler) *Req

OnRequestedRangeNotSatisfiable is a shorthand for On(StatusIsRequestedRangeNotSatisfiable, responseHandler). It matches status code 416.

func (*Req) OnResetContent added in v1.4.0

func (r *Req) OnResetContent(responseHandler ResponseHandler) *Req

OnResetContent is a shorthand for On(StatusIsResetContent, responseHandler). It matches status code 205.

func (*Req) OnSeeOther added in v1.4.0

func (r *Req) OnSeeOther(responseHandler ResponseHandler) *Req

OnSeeOther is a shorthand for On(StatusIsSeeOther, responseHandler). It matches status code 303.

func (*Req) OnServerError added in v1.4.0

func (r *Req) OnServerError(responseHandler ResponseHandler) *Req

OnServerError is a shorthand for On(StatusIsServerError, responseHandler). It matches any status code greater than or equal to 500.

func (*Req) OnServiceUnavailable added in v1.4.0

func (r *Req) OnServiceUnavailable(responseHandler ResponseHandler) *Req

OnServiceUnavailable is a shorthand for On(StatusIsServiceUnavailable, responseHandler). It matches status code 503.

func (*Req) OnSuccess added in v1.4.0

func (r *Req) OnSuccess(responseHandler ResponseHandler) *Req

OnSuccess is a shorthand for On(StatusIsSuccess, responseHandler). It matches any status code in the range [200, 300). Usage:

OnSuccess(ThenUnmarshalJsonTo(&items)).
Send()

func (*Req) OnSwitchingProtocols added in v1.4.0

func (r *Req) OnSwitchingProtocols(responseHandler ResponseHandler) *Req

OnSwitchingProtocols is a shorthand for On(StatusIsSwitchingProtocols, responseHandler). It matches status code 101.

func (*Req) OnTeapot added in v1.4.0

func (r *Req) OnTeapot(responseHandler ResponseHandler) *Req

OnTeapot is a shorthand for On(StatusIsTeapot, responseHandler). It matches status code 418.

func (*Req) OnTemporaryRedirect added in v1.4.0

func (r *Req) OnTemporaryRedirect(responseHandler ResponseHandler) *Req

OnTemporaryRedirect is a shorthand for On(StatusIsTemporaryRedirect, responseHandler). It matches status code 307.

func (*Req) OnTooEarly added in v1.4.0

func (r *Req) OnTooEarly(responseHandler ResponseHandler) *Req

OnTooEarly is a shorthand for On(StatusIsTooEarly, responseHandler). It matches status code 425.

func (*Req) OnTooManyRequests added in v1.4.0

func (r *Req) OnTooManyRequests(responseHandler ResponseHandler) *Req

OnTooManyRequests is a shorthand for On(StatusIsTooManyRequests, responseHandler). It matches status code 429.

func (*Req) OnUnauthorized added in v1.4.0

func (r *Req) OnUnauthorized(responseHandler ResponseHandler) *Req

OnUnauthorized is a shorthand for On(StatusIsUnauthorized, responseHandler). It matches status code 401.

func (*Req) OnUnavailableForLegalReasons added in v1.4.0

func (r *Req) OnUnavailableForLegalReasons(responseHandler ResponseHandler) *Req

OnUnavailableForLegalReasons is a shorthand for On(StatusIsUnavailableForLegalReasons, responseHandler). It matches status code 451.

func (*Req) OnUnprocessableEntity added in v1.4.0

func (r *Req) OnUnprocessableEntity(responseHandler ResponseHandler) *Req

OnUnprocessableEntity is a shorthand for On(StatusIsUnprocessableEntity, responseHandler). It matches status code 422.

func (*Req) OnUnsupportedMediaType added in v1.4.0

func (r *Req) OnUnsupportedMediaType(responseHandler ResponseHandler) *Req

OnUnsupportedMediaType is a shorthand for On(StatusIsUnsupportedMediaType, responseHandler). It matches status code 415.

func (*Req) OnUpgradeRequired added in v1.4.0

func (r *Req) OnUpgradeRequired(responseHandler ResponseHandler) *Req

OnUpgradeRequired is a shorthand for On(StatusIsUpgradeRequired, responseHandler). It matches status code 426.

func (*Req) OnUseProxy added in v1.4.0

func (r *Req) OnUseProxy(responseHandler ResponseHandler) *Req

OnUseProxy is a shorthand for On(StatusIsUseProxy, responseHandler). It matches status code 305.

func (*Req) OnVariantAlsoNegotiates added in v1.4.0

func (r *Req) OnVariantAlsoNegotiates(responseHandler ResponseHandler) *Req

OnVariantAlsoNegotiates is a shorthand for On(StatusIsVariantAlsoNegotiates, responseHandler). It matches status code 506.

func (*Req) QueryBool

func (r *Req) QueryBool(name string, v bool) *Req

func (*Req) QueryBoolPtr

func (r *Req) QueryBoolPtr(name string, v *bool) *Req

func (*Req) QueryFloat32

func (r *Req) QueryFloat32(name string, v float32) *Req

func (*Req) QueryFloat32Ptr

func (r *Req) QueryFloat32Ptr(name string, v *float32) *Req

func (*Req) QueryFloat64

func (r *Req) QueryFloat64(name string, v float64) *Req

func (*Req) QueryFloat64Ptr

func (r *Req) QueryFloat64Ptr(name string, v *float64) *Req

func (*Req) QueryInt

func (r *Req) QueryInt(name string, v int) *Req

func (*Req) QueryInt8

func (r *Req) QueryInt8(name string, v int8) *Req

func (*Req) QueryInt8Ptr

func (r *Req) QueryInt8Ptr(name string, v *int8) *Req

func (*Req) QueryInt16

func (r *Req) QueryInt16(name string, v int16) *Req

func (*Req) QueryInt16Ptr

func (r *Req) QueryInt16Ptr(name string, v *int16) *Req

func (*Req) QueryInt32

func (r *Req) QueryInt32(name string, v int32) *Req

func (*Req) QueryInt32Ptr

func (r *Req) QueryInt32Ptr(name string, v *int32) *Req

func (*Req) QueryInt64

func (r *Req) QueryInt64(name string, v int64) *Req

func (*Req) QueryInt64Ptr

func (r *Req) QueryInt64Ptr(name string, v *int64) *Req

func (*Req) QueryIntPtr

func (r *Req) QueryIntPtr(name string, v *int) *Req

func (*Req) QueryString added in v1.0.0

func (r *Req) QueryString(name string, v string) *Req

func (*Req) QueryStringPtr

func (r *Req) QueryStringPtr(name string, v *string) *Req

func (*Req) QueryUint

func (r *Req) QueryUint(name string, v uint) *Req

func (*Req) QueryUint8

func (r *Req) QueryUint8(name string, v uint8) *Req

func (*Req) QueryUint8Ptr

func (r *Req) QueryUint8Ptr(name string, v *uint8) *Req

func (*Req) QueryUint16

func (r *Req) QueryUint16(name string, v uint16) *Req

func (*Req) QueryUint16Ptr

func (r *Req) QueryUint16Ptr(name string, v *uint16) *Req

func (*Req) QueryUint32

func (r *Req) QueryUint32(name string, v uint32) *Req

func (*Req) QueryUint32Ptr

func (r *Req) QueryUint32Ptr(name string, v *uint32) *Req

func (*Req) QueryUint64

func (r *Req) QueryUint64(name string, v uint64) *Req

func (*Req) QueryUint64Ptr

func (r *Req) QueryUint64Ptr(name string, v *uint64) *Req

func (*Req) QueryUintPtr

func (r *Req) QueryUintPtr(name string, v *uint) *Req

func (*Req) Send

func (r *Req) Send() error

func (*Req) TimeOutIn

func (r *Req) TimeOutIn(duration time.Duration) *Req

func (*Req) UserAgent

func (r *Req) UserAgent(userAgent string) *Req

type RequestModifier

type RequestModifier func(request *http.Request) (*http.Request, error)

type Requester

type Requester interface {
	GetBody() (io.Reader, error)
}

func BodyFormData

func BodyFormData(body map[string][]string) Requester

func BodyFormDataFromMap

func BodyFormDataFromMap(body map[string]string) Requester

func BodyJson

func BodyJson(body any) Requester

func BodyReader

func BodyReader(body io.Reader) Requester

func BodyString

func BodyString(body string) Requester

func BodyXml

func BodyXml(body any) Requester

type ResponseHandler

type ResponseHandler func(response *http.Response) error

ResponseHandler is the function you pass along with a status matcher in the On call. It can be

func ThenReturnError added in v1.3.0

func ThenReturnError(err error) ResponseHandler

ThenReturnError returns the provided error directly in case of status is matched Usage: On(StatusAny, ThenReturnError(errors.New("something happened")))

func ThenUnmarshalJsonAndReturnError added in v1.4.0

func ThenUnmarshalJsonAndReturnError(targetAsPointer any, err error) ResponseHandler

ThenUnmarshalJsonAndReturnError marshals the body to the pointer with ThenUnmarshalJsonTo and returns provided error. Usage: On(StatusAny, ThenUnmarshalJsonAndReturnError(&items, errors.New("request failed")))

func ThenUnmarshalJsonTo added in v1.3.0

func ThenUnmarshalJsonTo(targetAsPointer any) ResponseHandler

ThenUnmarshalJsonTo marshals the body to the pointer provided in the targetAsPointer argument. It checks if the type is pointer as well. It does not close the body because body is closed after this function is called by the caller Usage: On(StatusAny, ThenUnmarshalJsonTo(&items))

type ResponseModifier

type ResponseModifier func(response *http.Response, server error) (*http.Response, error)

type RetryConfig

type RetryConfig struct {
	MaxRetries         int
	InitialBackoff     time.Duration
	MaxBackoff         time.Duration
	BackoffMultiplier  float64
	CustomRetryChecker CustomRetryChecker
}

type StatusMatcher

type StatusMatcher interface {
	Match(statusCode int) bool
	Priority() int
}

func StatusAnyExcept

func StatusAnyExcept(statusCode int) StatusMatcher

StatusAnyExcept matches any status code except the one provided. It has the priority 8, and it is checked after StatusIsInformational, StatusIsSuccess, StatusIsRedirection, StatusIsClientError, StatusIsServerError. Usage: On(StatusAnyExcept(http.StatusOK),func(r *http.Response) error{})

func StatusAnyExceptOneOf

func StatusAnyExceptOneOf(statusCodes ...int) StatusMatcher

StatusAnyExceptOneOf matches any status code except those provided. It has the priority 9, and it is checked after StatusAnyExcept. Usage: On(StatusAnyExceptOneOf(http.StatusOK,http.StatusCreated),func(r *http.Response) error{})

func StatusIs

func StatusIs(expectedStatus int) StatusMatcher

StatusIs checks if the response status is the provided status code. It has the priority 1, and it has the top priority. Usage: On(StatusIs(http.StatusOK),func(r *http.Response) error{}) -> only matches when the status code is 200

func StatusIsOneOf

func StatusIsOneOf(statusCodes ...int) StatusMatcher

StatusIsOneOf checks if the response status is one of the provided codes. It has the priority 2, and it is checked after StatusIs. Usage: On(StatusIsOneOf(http.StatusOK,http.StatusCreated),func(r *http.Response) error{}) -> only matches when the status code is either 200,201

Directories

Path Synopsis
loggers
zero module

Jump to

Keyboard shortcuts

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