Documentation ¶
Overview ¶
Package httpsling is a wrapper for creating and sending http httpsling (e.g. for webhooks, external 3d party integrations)
Index ¶
- Constants
- Variables
- func DefaultBackoffStrategy(delay time.Duration) func(int) time.Duration
- func DefaultRetryIf(req *http.Request, resp *http.Response, err error) bool
- func ExponentialBackoffStrategy(initialInterval time.Duration, multiplier float64, ...) func(int) time.Duration
- func GetBuffer() *bytebufferpool.ByteBuffer
- func LinearBackoffStrategy(initialInterval time.Duration) func(int) time.Duration
- func PutBuffer(b *bytebufferpool.ByteBuffer)
- type AuthMethod
- type AuthType
- type BackoffStrategy
- type BasicAuth
- type BearerAuth
- type Client
- func (c *Client) AddDefaultHeader(key, value string)
- func (c *Client) AddMiddleware(middlewares ...Middleware)
- func (c *Client) Connect(path string) *RequestBuilder
- func (c *Client) Custom(path, method string) *RequestBuilder
- func (c *Client) DelDefaultCookie(name string)
- func (c *Client) DelDefaultHeader(key string)
- func (c *Client) Delete(path string) *RequestBuilder
- func (c *Client) Get(path string) *RequestBuilder
- func (c *Client) Head(path string) *RequestBuilder
- func (c *Client) InsecureSkipVerify() *Client
- func (c *Client) NewRequestBuilder(method, path string) *RequestBuilder
- func (c *Client) Options(path string) *RequestBuilder
- func (c *Client) Patch(path string) *RequestBuilder
- func (c *Client) Post(path string) *RequestBuilder
- func (c *Client) Put(path string) *RequestBuilder
- func (c *Client) RemoveProxy()
- func (c *Client) SetAuth(auth AuthMethod)
- func (c *Client) SetBaseURL(baseURL string)
- func (c *Client) SetCookieJar(jar *cookiejar.Jar)
- func (c *Client) SetDefaultAccept(accept string)
- func (c *Client) SetDefaultContentType(contentType string)
- func (c *Client) SetDefaultCookie(name, value string)
- func (c *Client) SetDefaultCookieJar() error
- func (c *Client) SetDefaultCookies(cookies map[string]string)
- func (c *Client) SetDefaultHeader(key, value string)
- func (c *Client) SetDefaultHeaders(headers *http.Header)
- func (c *Client) SetDefaultReferer(referer string)
- func (c *Client) SetDefaultTimeout(timeout time.Duration)
- func (c *Client) SetDefaultTransport(transport http.RoundTripper)
- func (c *Client) SetDefaultUserAgent(userAgent string)
- func (c *Client) SetHTTPClient(httpClient *http.Client)
- func (c *Client) SetJSONMarshal(marshalFunc func(v any) ([]byte, error))
- func (c *Client) SetJSONUnmarshal(unmarshalFunc func(data []byte, v any) error)
- func (c *Client) SetLogger(logger Logger) *Client
- func (c *Client) SetMaxRetries(maxRetries int) *Client
- func (c *Client) SetProxy(proxyURL string) error
- func (c *Client) SetRetryIf(retryIf RetryIfFunc) *Client
- func (c *Client) SetRetryStrategy(strategy BackoffStrategy) *Client
- func (c *Client) SetTLSConfig(config *tls.Config) *Client
- func (c *Client) SetXMLMarshal(marshalFunc func(v any) ([]byte, error))
- func (c *Client) SetXMLUnmarshal(unmarshalFunc func(data []byte, v any) error)
- func (c *Client) SetYAMLMarshal(marshalFunc func(v any) ([]byte, error))
- func (c *Client) SetYAMLUnmarshal(unmarshalFunc func(data []byte, v any) error)
- func (c *Client) Trace(path string) *RequestBuilder
- type Config
- type CustomAuth
- type Decoder
- type DefaultLogger
- type Encoder
- type File
- type FormEncoder
- type JSONDecoder
- type JSONEncoder
- type Level
- type Logger
- type Middleware
- type MiddlewareHandlerFunc
- type RequestBuilder
- func (b *RequestBuilder) Accept(accept string) *RequestBuilder
- func (b *RequestBuilder) AddHeader(key, value string) *RequestBuilder
- func (b *RequestBuilder) AddMiddleware(middlewares ...Middleware)
- func (b *RequestBuilder) Auth(auth AuthMethod) *RequestBuilder
- func (b *RequestBuilder) Body(body interface{}) *RequestBuilder
- func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder
- func (b *RequestBuilder) Cookie(key, value string) *RequestBuilder
- func (b *RequestBuilder) Cookies(cookies map[string]string) *RequestBuilder
- func (b *RequestBuilder) DelCookie(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelFile(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelFormField(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelHeader(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelPathParam(key ...string) *RequestBuilder
- func (b *RequestBuilder) DelQuery(key ...string) *RequestBuilder
- func (b *RequestBuilder) File(key, filename string, content io.ReadCloser) *RequestBuilder
- func (b *RequestBuilder) Files(files ...*File) *RequestBuilder
- func (b *RequestBuilder) Form(v any) *RequestBuilder
- func (b *RequestBuilder) FormField(key, val string) *RequestBuilder
- func (b *RequestBuilder) FormFields(fields any) *RequestBuilder
- func (b *RequestBuilder) Header(key, value string) *RequestBuilder
- func (b *RequestBuilder) Headers(headers http.Header) *RequestBuilder
- func (b *RequestBuilder) JSONBody(v interface{}) *RequestBuilder
- func (b *RequestBuilder) MaxRetries(maxRetries int) *RequestBuilder
- func (b *RequestBuilder) Method(method string) *RequestBuilder
- func (b *RequestBuilder) Path(path string) *RequestBuilder
- func (b *RequestBuilder) PathParam(key, value string) *RequestBuilder
- func (b *RequestBuilder) PathParams(params map[string]string) *RequestBuilder
- func (b *RequestBuilder) Queries(params url.Values) *RequestBuilder
- func (b *RequestBuilder) QueriesStruct(queryStruct interface{}) *RequestBuilder
- func (b *RequestBuilder) Query(key, value string) *RequestBuilder
- func (b *RequestBuilder) RawBody(v []byte) *RequestBuilder
- func (b *RequestBuilder) Referer(referer string) *RequestBuilder
- func (b *RequestBuilder) RetryIf(retryIf RetryIfFunc) *RequestBuilder
- func (b *RequestBuilder) RetryStrategy(strategy BackoffStrategy) *RequestBuilder
- func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)
- func (b *RequestBuilder) Stream(callback StreamCallback) *RequestBuilder
- func (b *RequestBuilder) StreamDone(callback StreamDoneCallback) *RequestBuilder
- func (b *RequestBuilder) StreamErr(callback StreamErrCallback) *RequestBuilder
- func (b *RequestBuilder) TextBody(v string) *RequestBuilder
- func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder
- func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder
- func (b *RequestBuilder) XMLBody(v interface{}) *RequestBuilder
- func (b *RequestBuilder) YAMLBody(v interface{}) *RequestBuilder
- type Response
- func (r *Response) Body() []byte
- func (r *Response) Close() error
- func (r *Response) ContentLength() int
- func (r *Response) ContentType() string
- func (r *Response) Cookies() []*http.Cookie
- func (r *Response) Header() http.Header
- func (r *Response) IsContentType(contentType string) bool
- func (r *Response) IsEmpty() bool
- func (r *Response) IsJSON() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) IsXML() bool
- func (r *Response) IsYAML() bool
- func (r *Response) Location() (*url.URL, error)
- func (r *Response) Save(v any) error
- func (r *Response) Scan(v interface{}) error
- func (r *Response) ScanJSON(v interface{}) error
- func (r *Response) ScanXML(v interface{}) error
- func (r *Response) ScanYAML(v interface{}) error
- func (r *Response) Status() string
- func (r *Response) StatusCode() int
- func (r *Response) String() string
- func (r *Response) URL() *url.URL
- type RetryConfig
- type RetryIfFunc
- type StreamCallback
- type StreamDoneCallback
- type StreamErrCallback
- type XMLDecoder
- type XMLEncoder
- type YAMLDecoder
- type YAMLEncoder
Constants ¶
const ( // Authentication HeaderAuthorization = "Authorization" HeaderProxyAuthenticate = "Proxy-Authenticate" HeaderProxyAuthorization = "Proxy-Authorization" HeaderWWWAuthenticate = "WWW-Authenticate" // Caching HeaderAge = "Age" HeaderCacheControl = "Cache-Control" HeaderClearSiteData = "Clear-Site-Data" HeaderExpires = "Expires" HeaderPragma = "Pragma" HeaderWarning = "Warning" // Client hints HeaderAcceptCH = "Accept-CH" HeaderAcceptCHLifetime = "Accept-CH-Lifetime" HeaderContentDPR = "Content-DPR" HeaderDPR = "DPR" HeaderEarlyData = "Early-Data" HeaderSaveData = "Save-Data" HeaderViewportWidth = "Viewport-Width" HeaderWidth = "Width" // Conditionals HeaderETag = "ETag" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderLastModified = "Last-Modified" HeaderVary = "Vary" // Connection management HeaderConnection = "Connection" HeaderKeepAlive = "Keep-Alive" HeaderProxyConnection = "Proxy-Connection" // Content negotiation HeaderAccept = "Accept" HeaderAcceptCharset = "Accept-Charset" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" // Controls HeaderCookie = "Cookie" HeaderExpect = "Expect" HeaderMaxForwards = "Max-Forwards" HeaderSetCookie = "Set-Cookie" // CORS 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" HeaderOrigin = "Origin" HeaderTimingAllowOrigin = "Timing-Allow-Origin" HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" // Do Not Track HeaderDNT = "DNT" HeaderTk = "Tk" // Downloads HeaderContentDisposition = "Content-Disposition" // Message body information HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentLocation = "Content-Location" HeaderContentType = "Content-Type" // Content Types ContentTypeForm = "application/x-www-form-urlencoded" // https://datatracker.ietf.org/doc/html/rfc1866 ContentTypeMultipart = "multipart/form-data" // https://datatracker.ietf.org/doc/html/rfc2388 ContentTypeJSON = "application/json" // https://datatracker.ietf.org/doc/html/rfc4627 ContentTypeJSONUTF8 = "application/json;charset=utf-8" // https://datatracker.ietf.org/doc/html/rfc4627 ContentTypeXML = "application/xml" // https://datatracker.ietf.org/doc/html/rfc3023 ContentTypeXMLUTF8 = "application/xml;charset=utf-8" ContentTypeYAML = "application/yaml" // https://www.rfc-editor.org/rfc/rfc9512.html ContentTypeYAMLUTF8 = "application/yaml;charset=utf-8" ContentTypeText = "text/plain" ContentTypeApplicationOctetStream = "application/octet-stream" // Proxies HeaderForwarded = "Forwarded" HeaderVia = "Via" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedProto = "X-Forwarded-Proto" // Redirects HeaderLocation = "Location" // Request context HeaderFrom = "From" HeaderHost = "Host" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderUserAgent = "User-Agent" // Response context HeaderAllow = "Allow" HeaderServer = "Server" // Range requests. HeaderAcceptRanges = "Accept-Ranges" HeaderContentRange = "Content-Range" HeaderIfRange = "If-Range" HeaderRange = "Range" // Security HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderCrossOriginResourcePolicy = "Cross-Origin-Resource-Policy" HeaderExpectCT = "Expect-CT" HeaderFeaturePolicy = "Feature-Policy" HeaderPublicKeyPins = "Public-Key-Pins" HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXDownloadOptions = "X-Download-Options" HeaderXFrameOptions = "X-Frame-Options" HeaderXPoweredBy = "X-Powered-By" HeaderXXSSProtection = "X-XSS-Protection" // Server-sent event HeaderLastEventID = "Last-Event-ID" HeaderNEL = "NEL" HeaderPingFrom = "Ping-From" HeaderPingTo = "Ping-To" HeaderReportTo = "Report-To" // Transfer coding HeaderTE = "TE" HeaderTrailer = "Trailer" HeaderTransferEncoding = "Transfer-Encoding" // WebSockets HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" /* #nosec G101 */ HeaderSecWebSocketKey = "Sec-WebSocket-Key" HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" HeaderSecWebSocketVersion = "Sec-WebSocket-Version" // Other HeaderAcceptPatch = "Accept-Patch" HeaderAcceptPushPolicy = "Accept-Push-Policy" HeaderAcceptSignature = "Accept-Signature" HeaderAltSvc = "Alt-Svc" HeaderDate = "Date" HeaderIndex = "Index" HeaderLargeAllocation = "Large-Allocation" HeaderLink = "Link" HeaderPushPolicy = "Push-Policy" HeaderRetryAfter = "Retry-After" HeaderServerTiming = "Server-Timing" HeaderSignature = "Signature" HeaderSignedHeaders = "Signed-Headers" HeaderSourceMap = "SourceMap" HeaderUpgrade = "Upgrade" HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" HeaderXPingback = "X-Pingback" HeaderXRequestedWith = "X-Requested-With" HeaderXRobotsTag = "X-Robots-Tag" HeaderXUACompatible = "X-UA-Compatible" )
Variables ¶
var ( // ErrUnsupportedContentType is returned when the content type is unsupported ErrUnsupportedContentType = errors.New("unsupported content type") // ErrUnsupportedDataType is returned when the data type is unsupported ErrUnsupportedDataType = errors.New("unsupported data type") // ErrEncodingFailed is returned when the encoding fails ErrEncodingFailed = errors.New("encoding failed") // ErrRequestCreationFailed is returned when the request cannot be created ErrRequestCreationFailed = errors.New("failed to create request") // ErrResponseReadFailed is returned when the response cannot be read ErrResponseReadFailed = errors.New("failed to read response") // ErrUnsupportedScheme is returned when the proxy scheme is unsupported ErrUnsupportedScheme = errors.New("unsupported proxy scheme") // ErrUnsupportedFormFieldsType is returned when the form fields type is unsupported ErrUnsupportedFormFieldsType = errors.New("unsupported form fields type") // ErrNotSupportSaveMethod is returned when the provided type for saving is not supported ErrNotSupportSaveMethod = errors.New("the provided type for saving is not supported") // ErrInvalidTransportType is returned when the transport type is invalid ErrInvalidTransportType = errors.New("invalid transport type") // ErrResponseNil is returned when the response is nil ErrResponseNil = errors.New("response is nil") // ErrFailedToCloseResponseBody is returned when the response body cannot be closed ErrFailedToCloseResponseBody = errors.New("failed to close response body") // ErrMapper ErrMapper = "%w: %v" )
var DefaultFormEncoder = &FormEncoder{}
DefaultFormEncoder instance
var DefaultJSONDecoder = &JSONDecoder{ UnmarshalFunc: json.Unmarshal, }
DefaultJSONDecoder instance using the standard json.Unmarshal function
var DefaultJSONEncoder = &JSONEncoder{ MarshalFunc: json.Marshal, }
DefaultJSONEncoder instance using the standard json.Marshal function
var DefaultXMLDecoder = &XMLDecoder{ UnmarshalFunc: xml.Unmarshal, }
DefaultXMLDecoder instance using the standard xml.Unmarshal function
var DefaultXMLEncoder = &XMLEncoder{ MarshalFunc: xml.Marshal, }
DefaultXMLEncoder instance using the standard xml.Marshal function
var DefaultYAMLDecoder = &YAMLDecoder{
UnmarshalFunc: yaml.Unmarshal,
}
DefaultYAMLDecoder instance using the goccy/go-yaml Unmarshal function
var DefaultYAMLEncoder = &YAMLEncoder{
MarshalFunc: yaml.Marshal,
}
DefaultYAMLEncoder instance using the goccy/go-yaml Marshal function
Functions ¶
func DefaultBackoffStrategy ¶
DefaultBackoffStrategy provides a simple constant delay between retries
func DefaultRetryIf ¶
DefaultRetryIf is a simple retry condition that retries on 5xx status codes
func ExponentialBackoffStrategy ¶
func ExponentialBackoffStrategy(initialInterval time.Duration, multiplier float64, maxBackoffTime time.Duration) func(int) time.Duration
ExponentialBackoffStrategy increases the delay exponentially with each retry attempt
func GetBuffer ¶
func GetBuffer() *bytebufferpool.ByteBuffer
GetBuffer retrieves a buffer from the pool
func LinearBackoffStrategy ¶
LinearBackoffStrategy increases the delay linearly with each retry attempt
func PutBuffer ¶
func PutBuffer(b *bytebufferpool.ByteBuffer)
PutBuffer returns a buffer to the pool
Types ¶
type AuthMethod ¶
type AuthMethod interface { // Apply adds the authentication method to the request Apply(req *http.Request) // Valid checks if the authentication method is valid Valid() bool }
AuthMethod defines the interface for applying authentication strategies to httpsling
type AuthType ¶ added in v0.6.1
type AuthType string
AuthType represents the type of authentication method
type BackoffStrategy ¶
BackoffStrategy defines a function that returns the delay before the next retry
type BasicAuth ¶
BasicAuth represents HTTP Basic Authentication credentials
type BearerAuth ¶
type BearerAuth struct {
Token string
}
BearerAuth represents an OAuth 2.0 Bearer token
func (BearerAuth) Apply ¶
func (b BearerAuth) Apply(req *http.Request)
Apply adds the Bearer token to the request's Authorization header
func (BearerAuth) Valid ¶
func (b BearerAuth) Valid() bool
Valid checks if the Bearer token is present
type Client ¶
type Client struct { // BaseURL is the base URL for all httpsling made by this client BaseURL string // Headers are the default headers to be sent with each request Headers *http.Header // Cookies are the default cookies to be sent with each request Cookies []*http.Cookie // Middlewares are the request/response manipulation middlewares Middlewares []Middleware // TLSConfig is the TLS configuration for the client TLSConfig *tls.Config // MaxRetries is the maximum number of retry attempts MaxRetries int // RetryStrategy is the backoff strategy for retries RetryStrategy BackoffStrategy // RetryIf is the custom retry condition function RetryIf RetryIfFunc // HTTPClient is the underlying HTTP client HTTPClient *http.Client // JSONEncoder is the JSON encoder for the client JSONEncoder Encoder // JSONDecoder is the JSON decoder for the client JSONDecoder Decoder // XMLEncoder is the XML encoder for the client XMLEncoder Encoder // XMLDecoder is the XML decoder for the client XMLDecoder Decoder // YAMLEncoder is the YAML encoder for the client YAMLEncoder Encoder // YAMLDecoder is the YAML decoder for the client YAMLDecoder Decoder // Logger is the logger instance for the client Logger Logger // auth is the authentication method for the client Auth AuthMethod // contains filtered or unexported fields }
Client represents an HTTP client and is the main control mechanism for making HTTP requests
func (*Client) AddDefaultHeader ¶
AddDefaultHeader adds a default header
func (*Client) AddMiddleware ¶
func (c *Client) AddMiddleware(middlewares ...Middleware)
AddMiddleware adds a middleware to the client
func (*Client) Connect ¶
func (c *Client) Connect(path string) *RequestBuilder
Connect initiates a CONNECT request
func (*Client) Custom ¶
func (c *Client) Custom(path, method string) *RequestBuilder
Custom initiates a custom request
func (*Client) DelDefaultCookie ¶
DelDefaultCookie removes a default cookie from the client
func (*Client) DelDefaultHeader ¶
DelDefaultHeader removes a default header
func (*Client) Delete ¶
func (c *Client) Delete(path string) *RequestBuilder
Delete initiates a DELETE request
func (*Client) Head ¶
func (c *Client) Head(path string) *RequestBuilder
Head initiates a HEAD request
func (*Client) InsecureSkipVerify ¶
InsecureSkipVerify sets the TLS configuration to skip certificate verification
func (*Client) NewRequestBuilder ¶
func (c *Client) NewRequestBuilder(method, path string) *RequestBuilder
NewRequestBuilder creates a new RequestBuilder with default settings
func (*Client) Options ¶
func (c *Client) Options(path string) *RequestBuilder
Options initiates an OPTIONS request
func (*Client) Patch ¶
func (c *Client) Patch(path string) *RequestBuilder
Patch initiates a PATCH request
func (*Client) Post ¶
func (c *Client) Post(path string) *RequestBuilder
Post initiates a POST request
func (*Client) RemoveProxy ¶
func (c *Client) RemoveProxy()
RemoveProxy clears any configured proxy, allowing direct connections
func (*Client) SetAuth ¶
func (c *Client) SetAuth(auth AuthMethod)
SetAuth configures an authentication method for the client
func (*Client) SetBaseURL ¶
SetBaseURL sets the base URL for the client
func (*Client) SetCookieJar ¶ added in v0.6.0
SetDefaultCookieJar sets the default cookie jar for the client
func (*Client) SetDefaultAccept ¶
SetDefaultAccept sets the default accept header for the client
func (*Client) SetDefaultContentType ¶
SetDefaultContentType sets the default content type for the client
func (*Client) SetDefaultCookie ¶
SetDefaultCookie sets a default cookie for the client
func (*Client) SetDefaultCookieJar ¶
SetDefaultCookieJar sets the creates a new cookie jar and sets it for the client
func (*Client) SetDefaultCookies ¶
SetDefaultCookies sets the default cookies for the client
func (*Client) SetDefaultHeader ¶
SetDefaultHeader adds or updates a default header
func (*Client) SetDefaultHeaders ¶
SetDefaultHeaders sets the default headers for the client
func (*Client) SetDefaultReferer ¶
SetDefaultReferer sets the default referer for the client
func (*Client) SetDefaultTimeout ¶
SetDefaultTimeout sets the default timeout for the client
func (*Client) SetDefaultTransport ¶
func (c *Client) SetDefaultTransport(transport http.RoundTripper)
SetDefaultTransport sets the default transport for the client
func (*Client) SetDefaultUserAgent ¶
SetDefaultUserAgent sets the default user agent for the client
func (*Client) SetHTTPClient ¶
SetHTTPClient sets the HTTP client for the client
func (*Client) SetJSONMarshal ¶
SetJSONMarshal sets the JSON marshal function for the client's JSONEncoder
func (*Client) SetJSONUnmarshal ¶
SetJSONUnmarshal sets the JSON unmarshal function for the client's JSONDecoder
func (*Client) SetMaxRetries ¶
SetMaxRetries sets the maximum number of retry attempts
func (*Client) SetProxy ¶
SetProxy configures the client to use a proxy. Supports http, https, and socks5 proxies
func (*Client) SetRetryIf ¶
func (c *Client) SetRetryIf(retryIf RetryIfFunc) *Client
SetRetryIf sets the custom retry condition function
func (*Client) SetRetryStrategy ¶
func (c *Client) SetRetryStrategy(strategy BackoffStrategy) *Client
SetRetryStrategy sets the backoff strategy for retries
func (*Client) SetTLSConfig ¶
SetTLSConfig sets the TLS configuration for the client
func (*Client) SetXMLMarshal ¶
SetXMLMarshal sets the XML marshal function for the client's XMLEncoder
func (*Client) SetXMLUnmarshal ¶
SetXMLUnmarshal sets the XML unmarshal function for the client's XMLDecoder
func (*Client) SetYAMLMarshal ¶
SetYAMLMarshal sets the YAML marshal function for the client's YAMLEncoder
func (*Client) SetYAMLUnmarshal ¶
SetYAMLUnmarshal sets the YAML unmarshal function for the client's YAMLDecoder
func (*Client) Trace ¶
func (c *Client) Trace(path string) *RequestBuilder
Trace initiates a TRACE request
type Config ¶
type Config struct { // The base URL for all httpsling made by this client BaseURL string // Default headers to be sent with each request Headers *http.Header // Default Cookies to be sent with each request Cookies map[string]string // Timeout for httpsling Timeout time.Duration // Cookie jar for the client CookieJar *cookiejar.Jar // Middlewares for request/response manipulation Middlewares []Middleware // TLS configuration for the client TLSConfig *tls.Config // Custom transport for the client Transport http.RoundTripper // Maximum number of retry attempts MaxRetries int // RetryStrategy defines the backoff strategy for retries RetryStrategy BackoffStrategy // RetryIf defines the custom retry condition function RetryIf RetryIfFunc // Logger instance for the client Logger Logger }
Config sets up the initial configuration for the HTTP client - you need to initialize multiple if you want the behaviors to be different
type CustomAuth ¶
type CustomAuth struct {
Header string
}
CustomAuth allows for custom Authorization header values
func (CustomAuth) Apply ¶
func (c CustomAuth) Apply(req *http.Request)
Apply sets a custom Authorization header value
func (CustomAuth) Valid ¶
func (c CustomAuth) Valid() bool
Valid checks if the custom Authorization header value is present
type Decoder ¶
type Decoder interface { // Decode decodes the data from the reader into the provided value Decode(r io.Reader, v any) error }
Decoder is the interface that wraps the Decode method
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger is a default logger that uses `slog` as the underlying logger
func (*DefaultLogger) Debugf ¶
func (l *DefaultLogger) Debugf(format string, v ...any)
Debugf logs a message at the Debug level
func (*DefaultLogger) Errorf ¶
func (l *DefaultLogger) Errorf(format string, v ...any)
Errorf logs a message at the Error level
func (*DefaultLogger) Infof ¶
func (l *DefaultLogger) Infof(format string, v ...any)
Infof logs a message at the Info level
func (*DefaultLogger) SetLevel ¶
func (l *DefaultLogger) SetLevel(level Level)
SetLevel sets the log level of the logger
func (*DefaultLogger) Warnf ¶
func (l *DefaultLogger) Warnf(format string, v ...any)
Warnf logs a message at the Warn level
type Encoder ¶
type Encoder interface { // Encode encodes the provided value into a reader Encode(v any) (io.Reader, error) // ContentType returns the content type of the encoded data ContentType() string }
Encoder is the interface that wraps the Encode method
type File ¶
type File struct { // Name is the form field name Name string // FileName is the file name FileName string // Content is the file content Content io.ReadCloser // FileMime is the file mime type FileMime string }
File represents a form file
func (*File) SetContent ¶
func (f *File) SetContent(content io.ReadCloser)
SetContent sets the content of the file
func (*File) SetFileName ¶
SetFileName sets the file name
type JSONDecoder ¶
JSONDecoder handles decoding of JSON data
type JSONEncoder ¶
type JSONEncoder struct { // MarshalFunc is the custom marshal function to use MarshalFunc func(v any) ([]byte, error) }
JSONEncoder handles encoding of JSON data
func (*JSONEncoder) ContentType ¶
func (e *JSONEncoder) ContentType() string
ContentType returns the content type for JSON data
type Logger ¶
type Logger interface { Debugf(format string, v ...any) Infof(format string, v ...any) Warnf(format string, v ...any) Errorf(format string, v ...any) SetLevel(level Level) }
Logger is a logger interface that output logs with a format
type Middleware ¶
type Middleware func(next MiddlewareHandlerFunc) MiddlewareHandlerFunc
Middleware takes MiddlewareHandlerFunc and wraps around a next function call, which can be another middleware or the final transport layer call
type MiddlewareHandlerFunc ¶
MiddlewareHandlerFunc defines a function that takes an http.Request and returns an http.Response
type RequestBuilder ¶
type RequestBuilder struct { // BeforeRequest is a hook that can be used to modify the request object // before the request has been fired. This is useful for adding authentication // and other functionality not provided in this library BeforeRequest func(req *http.Request) error // contains filtered or unexported fields }
RequestBuilder facilitates building and executing HTTP requests
func (*RequestBuilder) Accept ¶
func (b *RequestBuilder) Accept(accept string) *RequestBuilder
Accept sets the Accept header for the request
func (*RequestBuilder) AddHeader ¶
func (b *RequestBuilder) AddHeader(key, value string) *RequestBuilder
AddHeader adds a header to the request
func (*RequestBuilder) AddMiddleware ¶
func (b *RequestBuilder) AddMiddleware(middlewares ...Middleware)
AddMiddleware adds a middleware to the request
func (*RequestBuilder) Auth ¶
func (b *RequestBuilder) Auth(auth AuthMethod) *RequestBuilder
Auth applies an authentication method to the request
func (*RequestBuilder) Body ¶
func (b *RequestBuilder) Body(body interface{}) *RequestBuilder
Body sets the request body
func (*RequestBuilder) ContentType ¶
func (b *RequestBuilder) ContentType(contentType string) *RequestBuilder
ContentType sets the Content-Type header for the request
func (*RequestBuilder) Cookie ¶
func (b *RequestBuilder) Cookie(key, value string) *RequestBuilder
Cookie adds a cookie to the request
func (*RequestBuilder) Cookies ¶
func (b *RequestBuilder) Cookies(cookies map[string]string) *RequestBuilder
Cookies method for map
func (*RequestBuilder) DelCookie ¶
func (b *RequestBuilder) DelCookie(key ...string) *RequestBuilder
DelCookie removes one or more cookies from the request
func (*RequestBuilder) DelFile ¶
func (b *RequestBuilder) DelFile(key ...string) *RequestBuilder
DelFile removes one or more files from the request
func (*RequestBuilder) DelFormField ¶
func (b *RequestBuilder) DelFormField(key ...string) *RequestBuilder
DelFormField removes one or more form fields
func (*RequestBuilder) DelHeader ¶
func (b *RequestBuilder) DelHeader(key ...string) *RequestBuilder
DelHeader removes one or more headers from the request
func (*RequestBuilder) DelPathParam ¶
func (b *RequestBuilder) DelPathParam(key ...string) *RequestBuilder
DelPathParam removes one or more path params fields from the RequestBuilder instance
func (*RequestBuilder) DelQuery ¶
func (b *RequestBuilder) DelQuery(key ...string) *RequestBuilder
DelQuery removes one or more query parameters from the request
func (*RequestBuilder) File ¶
func (b *RequestBuilder) File(key, filename string, content io.ReadCloser) *RequestBuilder
File adds a file to the request
func (*RequestBuilder) Files ¶
func (b *RequestBuilder) Files(files ...*File) *RequestBuilder
Files sets multiple files at once
func (*RequestBuilder) Form ¶
func (b *RequestBuilder) Form(v any) *RequestBuilder
Form sets form fields and files for the request
func (*RequestBuilder) FormField ¶
func (b *RequestBuilder) FormField(key, val string) *RequestBuilder
FormField adds or updates a form field
func (*RequestBuilder) FormFields ¶
func (b *RequestBuilder) FormFields(fields any) *RequestBuilder
FormFields sets multiple form fields at once
func (*RequestBuilder) Header ¶
func (b *RequestBuilder) Header(key, value string) *RequestBuilder
Header sets (or replaces) a header in the request
func (*RequestBuilder) Headers ¶
func (b *RequestBuilder) Headers(headers http.Header) *RequestBuilder
Headers set headers to the request
func (*RequestBuilder) JSONBody ¶
func (b *RequestBuilder) JSONBody(v interface{}) *RequestBuilder
JSONBody sets the request body as JSON
func (*RequestBuilder) MaxRetries ¶
func (b *RequestBuilder) MaxRetries(maxRetries int) *RequestBuilder
MaxRetries sets the maximum number of retry attempts
func (*RequestBuilder) Method ¶
func (b *RequestBuilder) Method(method string) *RequestBuilder
Method sets the HTTP method for the request
func (*RequestBuilder) Path ¶
func (b *RequestBuilder) Path(path string) *RequestBuilder
Path sets the URL path for the request
func (*RequestBuilder) PathParam ¶
func (b *RequestBuilder) PathParam(key, value string) *RequestBuilder
PathParam sets a single path param field and its value in the RequestBuilder instance
func (*RequestBuilder) PathParams ¶
func (b *RequestBuilder) PathParams(params map[string]string) *RequestBuilder
PathParams sets multiple path params fields and their values at one go in the RequestBuilder instance
func (*RequestBuilder) Queries ¶
func (b *RequestBuilder) Queries(params url.Values) *RequestBuilder
Queries adds query parameters to the request
func (*RequestBuilder) QueriesStruct ¶
func (b *RequestBuilder) QueriesStruct(queryStruct interface{}) *RequestBuilder
QueriesStruct adds query parameters to the request based on a struct tagged with url tags
func (*RequestBuilder) Query ¶
func (b *RequestBuilder) Query(key, value string) *RequestBuilder
Query adds a single query parameter to the request
func (*RequestBuilder) RawBody ¶
func (b *RequestBuilder) RawBody(v []byte) *RequestBuilder
RawBody sets the request body as raw bytes
func (*RequestBuilder) Referer ¶
func (b *RequestBuilder) Referer(referer string) *RequestBuilder
Referer sets the Referer header for the request
func (*RequestBuilder) RetryIf ¶
func (b *RequestBuilder) RetryIf(retryIf RetryIfFunc) *RequestBuilder
RetryIf sets the custom retry condition function
func (*RequestBuilder) RetryStrategy ¶
func (b *RequestBuilder) RetryStrategy(strategy BackoffStrategy) *RequestBuilder
RetryStrategy sets the backoff strategy for retries
func (*RequestBuilder) Send ¶
func (b *RequestBuilder) Send(ctx context.Context) (*Response, error)
Send executes the HTTP request
func (*RequestBuilder) Stream ¶
func (b *RequestBuilder) Stream(callback StreamCallback) *RequestBuilder
Stream sets the stream callback for the request
func (*RequestBuilder) StreamDone ¶
func (b *RequestBuilder) StreamDone(callback StreamDoneCallback) *RequestBuilder
StreamDone sets the done callback for the request.
func (*RequestBuilder) StreamErr ¶
func (b *RequestBuilder) StreamErr(callback StreamErrCallback) *RequestBuilder
StreamErr sets the error callback for the request.
func (*RequestBuilder) TextBody ¶
func (b *RequestBuilder) TextBody(v string) *RequestBuilder
TextBody sets the request body as plain text
func (*RequestBuilder) Timeout ¶
func (b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder
Timeout sets the request timeout
func (*RequestBuilder) UserAgent ¶
func (b *RequestBuilder) UserAgent(userAgent string) *RequestBuilder
UserAgent sets the User-Agent header for the request
func (*RequestBuilder) XMLBody ¶
func (b *RequestBuilder) XMLBody(v interface{}) *RequestBuilder
XMLBody sets the request body as XML
func (*RequestBuilder) YAMLBody ¶
func (b *RequestBuilder) YAMLBody(v interface{}) *RequestBuilder
YAMLBody sets the request body as YAML
type Response ¶
type Response struct { // RawResponse is the original HTTP response RawResponse *http.Response // BodyBytes is the response body as a juicy byte slice BodyBytes []byte // Context is the request context Context context.Context // Client is the HTTP client Client *Client // contains filtered or unexported fields }
Response represents an HTTP response
func NewResponse ¶
func NewResponse(ctx context.Context, resp *http.Response, client *Client, stream StreamCallback, streamErr StreamErrCallback, streamDone StreamDoneCallback) (*Response, error)
NewResponse creates a new wrapped response object leveraging the buffer pool
func (*Response) ContentLength ¶
ContentLength returns the length of the response body
func (*Response) ContentType ¶
ContentType returns the value of the HeaderContentType header
func (*Response) IsContentType ¶
IsContentType Checks if the response Content-Type header matches a given content type
func (*Response) StatusCode ¶
StatusCode returns the HTTP status code of the response
type RetryConfig ¶
type RetryConfig struct { // MaxRetries is the maximum number of retry attempts MaxRetries int // Strategy is the backoff strategy function Strategy BackoffStrategy // RetryIf is the custom retry condition function RetryIf RetryIfFunc }
RetryConfig defines the configuration for retrying requests
type RetryIfFunc ¶
RetryIfFunc defines the function signature for retry conditions
type StreamCallback ¶
StreamCallback is a callback function that is called when data is received
type StreamDoneCallback ¶
type StreamDoneCallback func()
StreamDoneCallback is a callback function that is called when the stream is done
type StreamErrCallback ¶
type StreamErrCallback func(error)
StreamErrCallback is a callback function that is called when an error occurs
type XMLDecoder ¶
XMLDecoder handles decoding of XML data
type XMLEncoder ¶
XMLEncoder handles encoding of XML data
func (*XMLEncoder) ContentType ¶
func (e *XMLEncoder) ContentType() string
ContentType returns the content type for XML data
type YAMLDecoder ¶
YAMLDecoder handles decoding of YAML data
type YAMLEncoder ¶
YAMLEncoder handles encoding of YAML data
func (*YAMLEncoder) ContentType ¶
func (e *YAMLEncoder) ContentType() string
ContentType returns the content type for YAML data