http

package
v0.36.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 19 Imported by: 10

Documentation

Overview

Package http provides an HTTP client with instrumentation and configuration support.

Index

Constants

View Source
const (
	HeaderAccept                          = "Accept"
	HeaderAcceptCH                        = "Accept-CH"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptCHLifetime                = "Accept-CH-Lifetime"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderAcceptPatch                     = "Accept-Patch"
	HeaderAcceptPushPolicy                = "Accept-Push-Policy"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderAcceptSignature                 = "Accept-Signature"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderAge                             = "Age"
	HeaderAllow                           = "Allow"
	HeaderAltSvc                          = "Alt-Svc"
	HeaderAuthorization                   = "Authorization"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderConnection                      = "Connection"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentDPR                      = "Content-DPR"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentRange                    = "Content-Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderContentType                     = "Content-Type"
	HeaderCookie                          = "Cookie"
	HeaderCookie2                         = "Cookie2"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderDate                            = "Date"
	HeaderDNT                             = "DNT"
	HeaderDPR                             = "DPR"
	HeaderEarlyData                       = "Early-Data"
	HeaderETag                            = "ETag"
	HeaderExpect                          = "Expect"
	HeaderExpectCT                        = "Expect-CT"
	HeaderExpires                         = "Expires"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderForwarded                       = "Forwarded"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfRange                         = "If-Range"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderIndex                           = "Index"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderLargeAllocation                 = "Large-Allocation"
	HeaderLastEventID                     = "Last-Event-ID"
	HeaderLastModified                    = "Last-Modified"
	HeaderLink                            = "Link"
	HeaderLocation                        = "Location"
	HeaderMaxForwards                     = "Max-Forwards"
	HeaderNEL                             = "NEL"
	HeaderOrigin                          = "Origin"
	HeaderPingFrom                        = "Ping-From"
	HeaderPingTo                          = "Ping-To"
	HeaderPragma                          = "Pragma"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderProxyConnection                 = "Proxy-Connection"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderPushPolicy                      = "Push-Policy"
	HeaderRange                           = "Range"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderReportTo                        = "Report-To"
	HeaderRetryAfter                      = "Retry-After"
	HeaderSaveData                        = "Save-Data"
	HeaderSecWebSocketAccept              = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions          = "Sec-WebSocket-Extensions" // #nosec G101
	HeaderSecWebSocketKey                 = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol            = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion             = "Sec-WebSocket-Version"
	HeaderServer                          = "Server"
	HeaderServerTiming                    = "Server-Timing"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderSignature                       = "Signature"
	HeaderSignedHeaders                   = "Signed-Headers"
	HeaderSourceMap                       = "SourceMap"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderTE                              = "TE"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderTk                              = "Tk"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderUpgrade                         = "Upgrade"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderUserAgent                       = "User-Agent"
	HeaderVary                            = "Vary"
	HeaderVia                             = "Via"
	HeaderViewportWidth                   = "Viewport-Width"
	HeaderWarning                         = "Warning"
	HeaderWidth                           = "Width"
	HeaderWWWAuthenticate                 = "WWW-Authenticate"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDNSPrefetchControl             = "X-DNS-Prefetch-Control"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPermittedCrossDomainPolicies   = "X-Permitted-Cross-Domain-Policies"
	HeaderXPingback                       = "X-Pingback"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXRequestedWith                  = "X-Requested-With"
	HeaderXRobotsTag                      = "X-Robots-Tag"
	HeaderXUACompatible                   = "X-UA-Compatible"
	HeaderXXSSProtection                  = "X-XSS-Protection"
)

HTTP header name constants.

View Source
const (
	HeaderAcceptQuery             = "Accept-Query" // RFC 10008, Section 3
	HeaderContentTransferEncoding = "Content-Transfer-Encoding"
	HeaderRateLimitLimit          = "RateLimit-Limit"     // draft-ietf-httpapi-ratelimit-headers
	HeaderRateLimitPolicy         = "RateLimit-Policy"    // draft-ietf-httpapi-ratelimit-headers
	HeaderRateLimitRemaining      = "RateLimit-Remaining" // draft-ietf-httpapi-ratelimit-headers
	HeaderRateLimitReset          = "RateLimit-Reset"     // draft-ietf-httpapi-ratelimit-headers
	HeaderRealIP                  = "X-Real-IP"
	HeaderTotalCount              = "X-Total-Count"
)

Additional HTTP header name constants.

View Source
const (
	ContentTypeJSON              = "application/json"
	ContentTypeXML               = "application/xml"
	ContentTypeFormURLEncoded    = "application/x-www-form-urlencoded"
	ContentTypeMultipartFormData = "multipart/form-data"
	ContentTypeOctetStream       = "application/octet-stream"
	ContentTypeTextPlain         = "text/plain"
	ContentTypeTextHTML          = "text/html"
)

Common HTTP content type constants.

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes as registered with IANA.

View Source
const (
	InstrumentationRequest = "http-client-request"
)

Instrumentation operation names for HTTP client events.

Variables

This section is empty.

Functions

func InstrRequest

func InstrRequest(op string, args ...any) (*Request, *Response, bool)

InstrRequest returns request and response if the operation is HTTP client request event.

func StatusCodeIsRedirect added in v0.35.0

func StatusCodeIsRedirect(statusCode int) bool

StatusCodeIsRedirect returns true if the status code indicates a redirect.

func StatusMessage added in v0.35.0

func StatusMessage(statusCode int) string

StatusMessage returns HTTP status message for the given status code.

Types

type BaseURL

type BaseURL string

BaseURL sets the base URL for the HTTP client requests.

type Client

type Client interface {
	// WithConfiguration returns a new client with specific named configuration.
	WithConfiguration(name string) (Client, error)
	// WithContext returns a new client with specified context.
	WithContext(ctx context.Context) Client
	// WithBaseURL returns a new client with specified base URL.
	WithBaseURL(url string) Client
	// WithOptions returns a new client with additional options applied.
	WithOptions(opt ...Option) Client

	// UserAgent returns client user agent.
	UserAgent() string
	// BaseURL returns client base URL.
	BaseURL() string

	// NewRequest creates a new HTTP request.
	//
	// The returned request must be released after use by calling ReleaseRequest.
	NewRequest() *Request
	// NewResponse creates a new HTTP response.
	//
	// The returned response must be released after use by calling ReleaseResponse.
	NewResponse() *Response
	// ReleaseRequest releases the HTTP request back to pool.
	ReleaseRequest(req *Request)
	// ReleaseResponse releases the HTTP response back to pool.
	ReleaseResponse(resp *Response)

	// Do sends an HTTP request and returns an HTTP response.
	Do(req *Request, resp *Response) error
	// Get sends an HTTP GET request and returns an HTTP response body.
	Get(url string, opt ...RequestOption) ([]byte, error)
	// GetJSON sends an HTTP GET request and unmarshals the response body into v.
	GetJSON(url string, v any, opt ...RequestOption) error
	// Query sends an HTTP QUERY request and returns an HTTP response body.
	Query(url string, body []byte, opt ...RequestOption) ([]byte, error)
	// QueryJSON sends an HTTP QUERY request and unmarshals response body into v.
	QueryJSON(url string, body, v any, opt ...RequestOption) error
	// QueryForm sends an HTTP QUERY request with form data and returns an HTTP response body.
	QueryForm(url string, form map[string][]string, opt ...RequestOption) ([]byte, error)
	// Post sends an HTTP POST request and returns an HTTP response body.
	Post(url string, body []byte, opt ...RequestOption) ([]byte, error)
	// PostJSON sends an HTTP POST request and unmarshals response body into v.
	PostJSON(url string, body, v any, opt ...RequestOption) error
	// PostForm sends an HTTP POST request with form data and returns an HTTP response body.
	PostForm(url string, form map[string][]string, opt ...RequestOption) ([]byte, error)
	// PostMultipartForm sends an HTTP POST request with multipart form data and returns an HTTP response body.
	PostMultipartForm(url string, form *multipart.Form, opt ...RequestOption) ([]byte, error)
	// Put sends an HTTP PUT request and returns an HTTP response body.
	Put(url string, body []byte, opt ...RequestOption) ([]byte, error)
	// PutJSON sends an HTTP PUT request and unmarshals response body into v.
	PutJSON(url string, body, v any, opt ...RequestOption) error
	// Patch sends an HTTP PATCH request and returns an HTTP response body.
	Patch(url string, body []byte, opt ...RequestOption) ([]byte, error)
	// PatchJSON sends an HTTP PATCH request and unmarshals response body into v.
	PatchJSON(url string, body, v any, opt ...RequestOption) error
	// Delete sends an HTTP DELETE request.
	Delete(url string, opt ...RequestOption) ([]byte, error)
	// DeleteJSON sends an HTTP DELETE request and unmarshals response body into v.
	DeleteJSON(url string, body, v any, opt ...RequestOption) error
}

Client is the interface that provides HTTP client.

func NewClient

func NewClient(opt ...Option) Client

NewClient creates a new HTTP client with the provided options.

type ClientProvider added in v0.16.0

type ClientProvider interface {
	// HTTPClient returns HTTP client instance.
	HTTPClient() Client
}

ClientProvider is the interface that provides HTTP client.

type Configuration

type Configuration struct {
	Clients map[string]NamedClient `mapstructure:"clients"`
}

Configuration represents the configuration for the HTTP client.

func (*Configuration) Validate

func (c *Configuration) Validate(valid *validation.Validate) error

Validate Metrics configuration section.

type DialContextFunc

type DialContextFunc func(ctx context.Context, network, addr string) (net.Conn, error)

DialContextFunc is a function that dials a network address.

type ErrorResponse

type ErrorResponse struct {
	Errors []*ErrorResponseError `json:"errors" yaml:"errors" xml:"Errors>Error"`
}

ErrorResponse represents an error response.

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

Error implements error interface.

type ErrorResponseError

type ErrorResponseError struct {
	Type    string `json:"type" yaml:"type" xml:"Type"`
	Message string `json:"message" yaml:"message" xml:"Message"`
}

ErrorResponseError is an error response error details.

type ForbiddenError

type ForbiddenError struct{}

ForbiddenError is an error that occurs when user access is denied.

func (ForbiddenError) Error

func (ForbiddenError) Error() string

func (ForbiddenError) StatusCode

func (ForbiddenError) StatusCode() int

StatusCode returns the HTTP 403 Forbidden status code.

type Instrumenter

type Instrumenter instrumenter.Instrumenter

Instrumenter is a function that instruments HTTP client operations.

type Method added in v0.35.0

type Method string

Method represents an HTTP request method.

const (
	MethodGet     Method = "GET"     // RFC 9110, 9.3.1
	MethodHead    Method = "HEAD"    // RFC 9110, 9.3.2
	MethodPost    Method = "POST"    // RFC 9110, 9.3.3
	MethodPut     Method = "PUT"     // RFC 9110, 9.3.4
	MethodDelete  Method = "DELETE"  // RFC 9110, 9.3.5
	MethodConnect Method = "CONNECT" // RFC 9110, 9.3.6
	MethodOptions Method = "OPTIONS" // RFC 9110, 9.3.7
	MethodTrace   Method = "TRACE"   // RFC 9110, 9.3.8
	MethodPatch   Method = "PATCH"   // RFC 5789
	MethodQuery   Method = "QUERY"   // RFC 10008
)

HTTP request methods.

func (Method) IsConnect added in v0.35.0

func (m Method) IsConnect() bool

IsConnect returns true if the method is CONNECT.

func (Method) IsDelete added in v0.35.0

func (m Method) IsDelete() bool

IsDelete returns true if the method is DELETE.

func (Method) IsGet added in v0.35.0

func (m Method) IsGet() bool

IsGet returns true if the method is GET.

func (Method) IsHead added in v0.35.0

func (m Method) IsHead() bool

IsHead returns true if the method is HEAD.

func (Method) IsOptions added in v0.35.0

func (m Method) IsOptions() bool

IsOptions returns true if the method is OPTIONS.

func (Method) IsPatch added in v0.35.0

func (m Method) IsPatch() bool

IsPatch returns true if the method is PATCH.

func (Method) IsPost added in v0.35.0

func (m Method) IsPost() bool

IsPost returns true if the method is POST.

func (Method) IsPut added in v0.35.0

func (m Method) IsPut() bool

IsPut returns true if the method is PUT.

func (Method) IsQuery added in v0.35.0

func (m Method) IsQuery() bool

IsQuery returns true if the method is QUERY.

func (Method) IsTrace added in v0.35.0

func (m Method) IsTrace() bool

IsTrace returns true if the method is TRACE.

func (Method) String added in v0.35.0

func (m Method) String() string

String returns the HTTP method as a string.

type NamedClient

type NamedClient struct {
	BaseURL string `mapstructure:"base_url" validate:"required http_url"`
}

NamedClient represents the configuration for the named client instance.

type NotFoundError

type NotFoundError struct {
	Resource string
}

NotFoundError is an error that occurs when searched resource is not found.

func (NotFoundError) Error

func (e NotFoundError) Error() string

func (NotFoundError) StatusCode

func (NotFoundError) StatusCode() int

StatusCode returns the HTTP 404 Not Found status code.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a functional option for configuring the HTTP client.

func Context

func Context(ctx context.Context) Option

Context sets the custom context for the HTTP client.

func Transport added in v0.20.0

func Transport(t fasthttp.RoundTripper) Option

Transport option for the HTTP client.

type Request

type Request struct {
	*fasthttp.Request
	// contains filtered or unexported fields
}

Request represents an HTTP request.

func (*Request) BaseURL

func (r *Request) BaseURL() string

BaseURL returns the base URL of the client.

func (*Request) Method added in v0.35.0

func (r *Request) Method() Method

Method returns the HTTP request method.

func (*Request) SetRequestURL

func (r *Request) SetRequestURL(u string) error

SetRequestURL sets the request URL.

type RequestFunc

type RequestFunc func(context.Context, *Request) error

RequestFunc is a function that modifies the HTTP request.

type RequestOption

type RequestOption interface {
	// contains filtered or unexported methods
}

RequestOption is a functional option for configuring the HTTP request.

func WithBody added in v0.24.0

func WithBody(body []byte) RequestOption

WithBody sets the content for the request body.

func WithHeader

func WithHeader(key, value string) RequestOption

WithHeader sets the specified header key and value for the request.

func WithQueryArg

func WithQueryArg(key string, value any, override ...bool) RequestOption

WithQueryArg sets the specified query argument key and value for the request.

type Response

type Response struct {
	*fasthttp.Response
}

Response represents HTTP response.

It is forbidden copying Response instances. Create new instances and use CopyTo instead.

Response instance MUST NOT be used from concurrently running goroutines.

func (Response) Error

func (r Response) Error() error

Error if the response status code is not 2xx.

func (Response) Success

func (r Response) Success() bool

Success returns true if the response status code is 2xx.

type ResponseFunc

type ResponseFunc func(context.Context, *Response, error) error

ResponseFunc is a function that modifies the HTTP response.

type ResponseStatusCode

type ResponseStatusCode interface {
	// StatusCode to be set for the response.
	StatusCode() int
}

ResponseStatusCode is an interface that error can implement to return status code that will be set for the response.

type RetryIf added in v0.18.0

type RetryIf fasthttp.RetryIfErrFunc

RetryIf is a function that determines if the request should be retried.

type StreamResponse added in v0.23.0

type StreamResponse bool

StreamResponse enables receiving response as a stream for the HTTP client.

type TLSConfig

type TLSConfig tls.Config

TLSConfig configures the TLS settings that client will use.

type UnauthorizedError

type UnauthorizedError struct{}

UnauthorizedError is an error that occurs when user is not authorized.

func (UnauthorizedError) Error

func (UnauthorizedError) Error() string

func (UnauthorizedError) StatusCode added in v0.15.4

func (UnauthorizedError) StatusCode() int

StatusCode returns the HTTP 401 Unauthorized status code.

type UserAgent

type UserAgent string

UserAgent sets the user agent for the HTTP client requests.

Jump to

Keyboard shortcuts

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