client

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package client provides the core HTTP client interfaces and implementations.

INTERNAL PACKAGE: This package is intended for internal use by the requests library. Users should import the main "github.com/sunerpy/requests" package instead, which re-exports all necessary types and functions.

The main package provides:

  • Type aliases: Request, Response, Result[T], RequestBuilder, etc.
  • HTTP methods: Get, Post, Put, Delete, Patch, Head, Options
  • Generic methods: GetJSON[T], PostJSON[T], etc.
  • Builder constructors: NewGet, NewPost, NewPut, NewDelete, NewPatch
  • Options: WithTimeout, WithHeader, WithQuery, etc.

Example usage (recommended):

import "github.com/sunerpy/requests"

// Simple GET request
resp, err := requests.Get("https://api.example.com/users")

// GET with JSON parsing
result, err := requests.GetJSON[User]("https://api.example.com/users/1")
user := result.Data()

// Using RequestBuilder
req, err := requests.NewPost("https://api.example.com/users").
    WithJSON(userData).
    WithHeader("Authorization", "Bearer token").
    Build()

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNilResponse        = errors.New("response is nil")
	ErrNilRequest         = errors.New("request is nil")
	ErrMissingURL         = errors.New("URL is required")
	ErrMissingMethod      = errors.New("method is required")
	ErrInvalidMethod      = errors.New("invalid HTTP method")
	ErrInvalidURL         = errors.New("invalid URL")
	ErrMaxRetriesExceeded = errors.New("max retries exceeded")
	ErrPanic              = errors.New("panic recovered in middleware")
)

Sentinel errors

Functions

func CombineRetryConditions

func CombineRetryConditions(conditions ...func(*models.Response, error) bool) func(*models.Response, error) bool

CombineRetryConditions combines multiple retry conditions with OR logic.

func CreateMockResponse

func CreateMockResponse(statusCode int, body []byte, headers http.Header) *models.Response

CreateMockResponse creates a models.Response for testing purposes.

func Decode

func Decode[T any](r *Response, decoder codec.Decoder) (T, error)

Decode is a generic function that parses the response body using a decoder.

func DecodeAuto

func DecodeAuto[T any](r *Response) (T, error)

DecodeAuto is a generic function that parses based on Content-Type.

func DefaultRetryCondition

func DefaultRetryCondition(resp *models.Response, err error) bool

DefaultRetryCondition is the default condition for retrying requests.

func Delete

func Delete(rawURL string, opts ...RequestOption) (*models.Response, error)

Delete performs a DELETE request and returns the response.

func DeleteWithContext

func DeleteWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)

DeleteWithContext performs a DELETE request with context.

func Get

func Get(rawURL string, opts ...RequestOption) (*models.Response, error)

============================================================================ Basic HTTP Methods - return (*models.Response, error) ============================================================================ Get performs a GET request and returns the response.

func GetBytes

func GetBytes(rawURL string, opts ...RequestOption) ([]byte, error)

GetBytes performs a GET request and returns the response body as bytes.

func GetString

func GetString(rawURL string, opts ...RequestOption) (string, error)

============================================================================ Convenience Methods ============================================================================ GetString performs a GET request and returns the response body as string.

func GetWithContext

func GetWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)

GetWithContext performs a GET request with context.

func Head(rawURL string, opts ...RequestOption) (*models.Response, error)

Head performs a HEAD request and returns the response.

func HeadWithContext

func HeadWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)

HeadWithContext performs a HEAD request with context.

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError checks if an error is a connection error.

func IsResponseError

func IsResponseError(err error) bool

IsResponseError checks if an error is a response error.

func IsTemporary

func IsTemporary(err error) bool

IsTemporary checks if an error is temporary and can be retried.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout checks if an error is a timeout error.

func JSON

func JSON[T any](r *Response) (T, error)

JSON is a generic function that parses the response body as JSON.

func MustJSON

func MustJSON[T any](r *Response) T

MustJSON parses JSON and panics on error.

func MustXML

func MustXML[T any](r *Response) T

MustXML parses XML and panics on error.

func Options

func Options(rawURL string, opts ...RequestOption) (*models.Response, error)

Options performs an OPTIONS request and returns the response.

func OptionsWithContext

func OptionsWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)

OptionsWithContext performs an OPTIONS request with context.

func Patch

func Patch(rawURL string, body any, opts ...RequestOption) (*models.Response, error)

Patch performs a PATCH request and returns the response.

func PatchWithContext

func PatchWithContext(ctx context.Context, rawURL string, body any, opts ...RequestOption) (*models.Response, error)

PatchWithContext performs a PATCH request with context.

func Post

func Post(rawURL string, body any, opts ...RequestOption) (*models.Response, error)

Post performs a POST request and returns the response.

func PostWithContext

func PostWithContext(ctx context.Context, rawURL string, body any, opts ...RequestOption) (*models.Response, error)

PostWithContext performs a POST request with context.

func PrepareBody

func PrepareBody(body any) (io.Reader, string, error)

PrepareBody converts the body to an io.Reader and returns the content type. This is exported for use by the main package.

func Put

func Put(rawURL string, body any, opts ...RequestOption) (*models.Response, error)

Put performs a PUT request and returns the response.

func PutWithContext

func PutWithContext(ctx context.Context, rawURL string, body any, opts ...RequestOption) (*models.Response, error)

PutWithContext performs a PUT request with context.

func ReleaseBuilder

func ReleaseBuilder(b *RequestBuilder)

ReleaseBuilder returns a RequestBuilder to the pool

func ReleaseConfig

func ReleaseConfig(c *RequestConfig)

ReleaseConfig returns a RequestConfig to the pool.

func RetryOn5xx

func RetryOn5xx(resp *models.Response, err error) bool

RetryOn5xx returns a retry condition that retries on 5xx errors.

func RetryOnNetworkError

func RetryOnNetworkError(resp *models.Response, err error) bool

RetryOnNetworkError returns a retry condition that only retries on network errors.

func RetryOnStatusCodes

func RetryOnStatusCodes(codes ...int) func(*models.Response, error) bool

RetryOnStatusCodes returns a retry condition that retries on specific status codes.

func SetDefaultClient

func SetDefaultClient(client HTTPClient)

SetDefaultClient sets the default HTTP client.

func XML

func XML[T any](r *Response) (T, error)

XML is a generic function that parses the response body as XML.

Types

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth holds basic authentication credentials.

type Client

type Client interface {
	// Do executes an HTTP request and returns the response.
	Do(req *Request) (*models.Response, error)
	// DoWithContext executes an HTTP request with context.
	DoWithContext(ctx context.Context, req *Request) (*models.Response, error)
	// Clone creates a copy of the client.
	Clone() Client
}

Client is the core HTTP client interface.

type ConnectionError

type ConnectionError struct {
	Op  string // Operation (e.g., "Dial", "TLS", "DNS")
	URL string // URL of the request
	Err error  // Underlying error
}

ConnectionError represents a network connection error.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error implements the error interface.

func (*ConnectionError) Is

func (e *ConnectionError) Is(target error) bool

Is reports whether target matches this error.

func (*ConnectionError) Temporary

func (e *ConnectionError) Temporary() bool

Temporary returns true if the error is temporary.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap returns the underlying error.

type DecodeError

type DecodeError struct {
	ContentType string // Content type being decoded
	Err         error  // Underlying error
}

DecodeError represents an error during response decoding.

func (*DecodeError) Error

func (e *DecodeError) Error() string

Error implements the error interface.

func (*DecodeError) Is

func (e *DecodeError) Is(target error) bool

Is reports whether target matches this error.

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

Unwrap returns the underlying error.

type EncodeError

type EncodeError struct {
	ContentType string // Content type being encoded
	Err         error  // Underlying error
}

EncodeError represents an error during request encoding.

func (*EncodeError) Error

func (e *EncodeError) Error() string

Error implements the error interface.

func (*EncodeError) Is

func (e *EncodeError) Is(target error) bool

Is reports whether target matches this error.

func (*EncodeError) Unwrap

func (e *EncodeError) Unwrap() error

Unwrap returns the underlying error.

type ErrorHook

type ErrorHook func(req *Request, err error, duration time.Duration)

ErrorHook is called when an error occurs.

func ErrorLoggingHook

func ErrorLoggingHook(logger func(format string, args ...any)) ErrorHook

ErrorLoggingHook creates an error hook that logs errors.

type FileUpload

type FileUpload struct {
	FieldName string
	FileName  string
	Reader    io.Reader
}

FileUpload represents a file to be uploaded.

type FileUploadConfig

type FileUploadConfig struct {
	FieldName string
	FileName  string
	FilePath  string
	Reader    any // io.Reader
	Size      int64
	Progress  ProgressCallback
}

FileUploadConfig holds file upload configuration.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is the interface for executing HTTP requests.

var DefaultHTTPClient HTTPClient = &http.Client{
	Timeout: 30 * time.Second,
}

DefaultHTTPClient is the default HTTP client used for requests.

type Handler

type Handler func(*Request) (*models.Response, error)

Handler is the next handler in the middleware chain.

type Hooks

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

Hooks manages request/response hooks using atomic operations for better performance.

func NewHooks

func NewHooks() *Hooks

NewHooks creates a new Hooks instance.

func (*Hooks) Clear

func (h *Hooks) Clear() *Hooks

Clear removes all registered hooks.

func (*Hooks) Clone

func (h *Hooks) Clone() *Hooks

Clone creates a copy of the hooks.

func (*Hooks) Len

func (h *Hooks) Len() int

Len returns the total number of registered hooks.

func (*Hooks) OnError

func (h *Hooks) OnError(hook ErrorHook) *Hooks

OnError registers an error hook.

func (*Hooks) OnRequest

func (h *Hooks) OnRequest(hook RequestHook) *Hooks

OnRequest registers a request hook.

func (*Hooks) OnResponse

func (h *Hooks) OnResponse(hook ResponseHook) *Hooks

OnResponse registers a response hook.

func (*Hooks) TriggerError

func (h *Hooks) TriggerError(req *Request, err error, duration time.Duration)

TriggerError calls all registered error hooks (lock-free).

func (*Hooks) TriggerRequest

func (h *Hooks) TriggerRequest(req *Request)

TriggerRequest calls all registered request hooks (lock-free).

func (*Hooks) TriggerResponse

func (h *Hooks) TriggerResponse(req *Request, resp *models.Response, duration time.Duration)

TriggerResponse calls all registered response hooks (lock-free).

type Method

type Method string

Method represents an HTTP method.

const (
	MethodGet     Method = "GET"
	MethodPost    Method = "POST"
	MethodPut     Method = "PUT"
	MethodDelete  Method = "DELETE"
	MethodPatch   Method = "PATCH"
	MethodHead    Method = "HEAD"
	MethodOptions Method = "OPTIONS"
	MethodConnect Method = "CONNECT"
	MethodTrace   Method = "TRACE"
)

HTTP methods as constants.

func (Method) HasRequestBody

func (m Method) HasRequestBody() bool

HasRequestBody returns true if the method typically has a request body.

func (Method) IsIdempotent

func (m Method) IsIdempotent() bool

IsIdempotent returns true if the method is idempotent.

func (Method) IsSafe

func (m Method) IsSafe() bool

IsSafe returns true if the method is safe (read-only).

func (Method) IsValid

func (m Method) IsValid() bool

IsValid checks if the method is a valid HTTP method.

func (Method) String

func (m Method) String() string

String returns the string representation of the method.

type MetricsHook

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

MetricsHook creates hooks for collecting metrics using atomic operations.

func NewMetricsHook

func NewMetricsHook() *MetricsHook

NewMetricsHook creates a new metrics hook.

func (*MetricsHook) ErrorHook

func (m *MetricsHook) ErrorHook() ErrorHook

ErrorHook returns an error hook for counting errors.

func (*MetricsHook) RequestHook

func (m *MetricsHook) RequestHook() RequestHook

RequestHook returns a request hook for counting requests.

func (*MetricsHook) Reset

func (m *MetricsHook) Reset()

Reset resets the metrics.

func (*MetricsHook) ResponseHook

func (m *MetricsHook) ResponseHook() ResponseHook

ResponseHook returns a response hook for counting responses.

func (*MetricsHook) Stats

func (m *MetricsHook) Stats() (requests, responses, errors int64, avgDuration time.Duration)

Stats returns the current metrics.

type Middleware

type Middleware interface {
	// Process handles the request and calls next to continue the chain.
	Process(req *Request, next Handler) (*models.Response, error)
}

Middleware defines the request/response middleware interface.

func AuthMiddleware

func AuthMiddleware(authHeader string) Middleware

AuthMiddleware creates a middleware that adds authorization header.

func BasicAuthMiddleware

func BasicAuthMiddleware(username, password string) Middleware

BasicAuthMiddleware creates a middleware that adds basic auth.

func BearerTokenMiddleware

func BearerTokenMiddleware(token string) Middleware

BearerTokenMiddleware creates a middleware that adds bearer token auth.

func ChainMiddleware

func ChainMiddleware(middlewares ...Middleware) Middleware

ChainMiddleware combines multiple middlewares into one.

func ConditionalMiddleware

func ConditionalMiddleware(condition func(*Request) bool, m Middleware) Middleware

ConditionalMiddleware creates a middleware that only executes if condition is true.

func HeaderMiddleware

func HeaderMiddleware(headers map[string]string) Middleware

HeaderMiddleware creates a middleware that adds headers to all requests.

func HooksMiddleware

func HooksMiddleware(hooks *Hooks) Middleware

HooksMiddleware creates a middleware that triggers hooks.

func LoggingMiddleware

func LoggingMiddleware(logger func(format string, args ...any)) Middleware

LoggingMiddleware creates a middleware that logs requests and responses.

func RecoveryMiddleware

func RecoveryMiddleware(onPanic func(req *Request, recovered any)) Middleware

RecoveryMiddleware creates a middleware that recovers from panics.

func RetryMiddleware

func RetryMiddleware(policy RetryPolicy) Middleware

RetryMiddleware creates a middleware that adds retry logic.

func UserAgentMiddleware

func UserAgentMiddleware(userAgent string) Middleware

UserAgentMiddleware creates a middleware that sets the User-Agent header.

type MiddlewareChain

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

MiddlewareChain manages a chain of middleware.

func NewMiddlewareChain

func NewMiddlewareChain(middlewares ...Middleware) *MiddlewareChain

NewMiddlewareChain creates a new middleware chain.

func (*MiddlewareChain) Clone

func (c *MiddlewareChain) Clone() *MiddlewareChain

Clone creates a copy of the middleware chain.

func (*MiddlewareChain) Execute

func (c *MiddlewareChain) Execute(req *Request, finalHandler Handler) (*models.Response, error)

Execute runs the middleware chain with the given handler as the final handler.

func (*MiddlewareChain) Len

func (c *MiddlewareChain) Len() int

Len returns the number of middlewares in the chain.

func (*MiddlewareChain) Use

Use adds a middleware to the chain.

func (*MiddlewareChain) UseFunc

func (c *MiddlewareChain) UseFunc(fn func(req *Request, next Handler) (*models.Response, error)) *MiddlewareChain

UseFunc adds a middleware function to the chain.

type MiddlewareFunc

type MiddlewareFunc func(req *Request, next Handler) (*models.Response, error)

MiddlewareFunc is a function adapter for Middleware interface.

func (MiddlewareFunc) Process

func (f MiddlewareFunc) Process(req *Request, next Handler) (*models.Response, error)

Process implements the Middleware interface.

type ProgressCallback

type ProgressCallback func(uploaded, total int64)

ProgressCallback is called during file upload to report progress.

type Request

type Request struct {
	Method  Method
	URL     *url.URL
	Headers http.Header
	Body    io.Reader
	Context context.Context
	// contains filtered or unexported fields
}

Request represents an HTTP request.

func (*Request) AddHeader

func (r *Request) AddHeader(key, value string)

AddHeader adds a header value to the request. Multiple values can be added for the same key.

func (*Request) Clone

func (r *Request) Clone() *Request

Clone creates a deep copy of the Request. Modifications to the original Request will not affect the clone, and vice versa.

func (*Request) SetHeader

func (r *Request) SetHeader(key, value string)

SetHeader sets a header value on the request. This replaces any existing values for the key.

type RequestBuilder

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

RequestBuilder provides a fluent interface for building HTTP requests.

func AcquireBuilder

func AcquireBuilder(method Method, rawURL string) *RequestBuilder

AcquireBuilder gets a RequestBuilder from the pool

func NewDelete

func NewDelete(rawURL string) *RequestBuilder

NewDelete creates a new DELETE request builder (short alias for NewDeleteRequest).

func NewDeleteRequest

func NewDeleteRequest(rawURL string) *RequestBuilder

NewDeleteRequest creates a new DELETE request builder.

func NewGet

func NewGet(rawURL string) *RequestBuilder

NewGet creates a new GET request builder (short alias for NewGetRequest).

func NewGetRequest

func NewGetRequest(rawURL string) *RequestBuilder

NewGetRequest creates a new GET request builder.

func NewPatch

func NewPatch(rawURL string) *RequestBuilder

NewPatch creates a new PATCH request builder (short alias for NewPatchRequest).

func NewPatchRequest

func NewPatchRequest(rawURL string) *RequestBuilder

NewPatchRequest creates a new PATCH request builder.

func NewPost

func NewPost(rawURL string) *RequestBuilder

NewPost creates a new POST request builder (short alias for NewPostRequest).

func NewPostRequest

func NewPostRequest(rawURL string) *RequestBuilder

NewPostRequest creates a new POST request builder.

func NewPut

func NewPut(rawURL string) *RequestBuilder

NewPut creates a new PUT request builder (short alias for NewPutRequest).

func NewPutRequest

func NewPutRequest(rawURL string) *RequestBuilder

NewPutRequest creates a new PUT request builder.

func NewRequest

func NewRequest(method Method, rawURL string) *RequestBuilder

NewRequest creates a new RequestBuilder with the specified method and URL. Uses lazy initialization for headers, query, and form to reduce allocations.

func (*RequestBuilder) Build

func (b *RequestBuilder) Build() (*Request, error)

Build constructs the final Request from the builder. Note: After calling Build(), the builder should not be reused unless Reset() is called. The headers are transferred by ownership to avoid allocation.

func (*RequestBuilder) BuildCopy

func (b *RequestBuilder) BuildCopy() (*Request, error)

BuildCopy constructs a Request while preserving the builder state. Use this if you need to reuse the builder after building.

func (*RequestBuilder) Clone

func (b *RequestBuilder) Clone() *RequestBuilder

Clone creates a copy of the builder.

func (*RequestBuilder) Do

func (b *RequestBuilder) Do() (*models.Response, error)

Do builds and executes the request, returning the response.

func (*RequestBuilder) GetBodyBytes

func (b *RequestBuilder) GetBodyBytes() []byte

GetBodyBytes returns the body bytes if available.

func (*RequestBuilder) GetFiles

func (b *RequestBuilder) GetFiles() []FileUpload

GetFiles returns the files to be uploaded.

func (*RequestBuilder) GetForm

func (b *RequestBuilder) GetForm() url.Values

GetForm returns a copy of the form values.

func (*RequestBuilder) GetHeaders

func (b *RequestBuilder) GetHeaders() http.Header

GetHeaders returns a copy of the current headers.

func (*RequestBuilder) GetMethod

func (b *RequestBuilder) GetMethod() Method

GetMethod returns the current method.

func (*RequestBuilder) GetQuery

func (b *RequestBuilder) GetQuery() url.Values

GetQuery returns a copy of the current query parameters.

func (*RequestBuilder) GetTimeout

func (b *RequestBuilder) GetTimeout() time.Duration

GetTimeout returns the timeout duration.

func (*RequestBuilder) GetURL

func (b *RequestBuilder) GetURL() string

GetURL returns the current URL.

func (*RequestBuilder) Reset

func (b *RequestBuilder) Reset()

Reset clears the builder for reuse

func (*RequestBuilder) WithBasicAuth

func (b *RequestBuilder) WithBasicAuth(username, password string) *RequestBuilder

WithBasicAuth adds basic authentication header.

func (*RequestBuilder) WithBearerToken

func (b *RequestBuilder) WithBearerToken(token string) *RequestBuilder

WithBearerToken adds bearer token authentication header.

func (*RequestBuilder) WithBody

func (b *RequestBuilder) WithBody(body io.Reader) *RequestBuilder

WithBody sets a raw body reader.

func (*RequestBuilder) WithBodyBytes

func (b *RequestBuilder) WithBodyBytes(data []byte) *RequestBuilder

WithBodyBytes sets the body from bytes.

func (*RequestBuilder) WithContext

func (b *RequestBuilder) WithContext(ctx context.Context) *RequestBuilder

WithContext sets the request context.

func (*RequestBuilder) WithEncoder

func (b *RequestBuilder) WithEncoder(encoder codec.Encoder, data any) *RequestBuilder

WithEncoder sets a custom encoder for the body data.

func (*RequestBuilder) WithFile

func (b *RequestBuilder) WithFile(fieldName, fileName string, reader io.Reader) *RequestBuilder

WithFile adds a file for multipart upload.

func (*RequestBuilder) WithForm

func (b *RequestBuilder) WithForm(data map[string]string) *RequestBuilder

WithForm sets the request body as form data.

func (*RequestBuilder) WithFormValues

func (b *RequestBuilder) WithFormValues(values url.Values) *RequestBuilder

WithFormValues sets the request body from url.Values.

func (*RequestBuilder) WithHeader

func (b *RequestBuilder) WithHeader(key, value string) *RequestBuilder

WithHeader adds a single header to the request.

func (*RequestBuilder) WithHeaders

func (b *RequestBuilder) WithHeaders(headers map[string]string) *RequestBuilder

WithHeaders adds multiple headers to the request.

func (*RequestBuilder) WithJSON

func (b *RequestBuilder) WithJSON(data any) *RequestBuilder

WithJSON sets the request body as JSON.

func (*RequestBuilder) WithMethod

func (b *RequestBuilder) WithMethod(method Method) *RequestBuilder

WithMethod sets the HTTP method.

func (*RequestBuilder) WithQuery

func (b *RequestBuilder) WithQuery(key, value string) *RequestBuilder

WithQuery adds a single query parameter. Uses fast path with slice storage to avoid map allocations.

func (*RequestBuilder) WithQueryParams

func (b *RequestBuilder) WithQueryParams(params map[string]string) *RequestBuilder

WithQueryParams adds multiple query parameters.

func (*RequestBuilder) WithTimeout

func (b *RequestBuilder) WithTimeout(d time.Duration) *RequestBuilder

WithTimeout sets the request timeout.

func (*RequestBuilder) WithURL

func (b *RequestBuilder) WithURL(rawURL string) *RequestBuilder

WithURL sets the request URL.

func (*RequestBuilder) WithXML

func (b *RequestBuilder) WithXML(data any) *RequestBuilder

WithXML sets the request body as XML.

type RequestConfig

type RequestConfig struct {
	Timeout          time.Duration
	Headers          http.Header
	Query            url.Values
	BasicAuth        *BasicAuth
	BearerToken      string
	Retry            *RetryPolicy
	Context          context.Context
	Files            []FileUploadConfig
	ProgressCallback ProgressCallback
}

RequestConfig holds the configuration for a request.

func AcquireConfig

func AcquireConfig() *RequestConfig

AcquireConfig gets a RequestConfig from the pool.

func NewRequestConfig

func NewRequestConfig() *RequestConfig

NewRequestConfig creates a new RequestConfig with default values.

func (*RequestConfig) Apply

func (c *RequestConfig) Apply(opts ...RequestOption)

Apply applies all options to the config.

func (*RequestConfig) ApplyToRequest

func (c *RequestConfig) ApplyToRequest(req *http.Request)

ApplyToRequest applies the config to an HTTP request.

func (*RequestConfig) Clone

func (c *RequestConfig) Clone() *RequestConfig

Clone creates a deep copy of the config.

func (*RequestConfig) Merge

func (c *RequestConfig) Merge(other *RequestConfig)

Merge merges another config into this one. Values from other take precedence if set.

func (*RequestConfig) Reset

func (c *RequestConfig) Reset()

Reset clears the config for reuse, keeping the underlying map allocations.

type RequestError

type RequestError struct {
	Op  string // Operation name (e.g., "Build", "Send", "Encode")
	URL string // URL of the request
	Err error  // Underlying error
}

RequestError represents an error during request building or sending.

func (*RequestError) Error

func (e *RequestError) Error() string

Error implements the error interface.

func (*RequestError) Is

func (e *RequestError) Is(target error) bool

Is reports whether target matches this error.

func (*RequestError) Unwrap

func (e *RequestError) Unwrap() error

Unwrap returns the underlying error.

type RequestHook

type RequestHook func(req *Request)

RequestHook is called before a request is sent.

func LoggingHook

func LoggingHook(logger func(format string, args ...any)) RequestHook

LoggingHook creates a request hook that logs requests.

type RequestOption

type RequestOption func(*RequestConfig)

RequestOption is a function that configures a RequestConfig.

func WithAccept

func WithAccept(accept string) RequestOption

WithAccept sets the Accept header.

func WithBasicAuth

func WithBasicAuth(username, password string) RequestOption

WithBasicAuth sets basic authentication.

func WithBearerToken

func WithBearerToken(token string) RequestOption

WithBearerToken sets bearer token authentication.

func WithContentType

func WithContentType(contentType string) RequestOption

WithContentType sets the Content-Type header.

func WithContext

func WithContext(ctx context.Context) RequestOption

WithContext sets the request context.

func WithFile

func WithFile(fieldName, filePath string) RequestOption

WithFile adds a file for upload by path.

func WithFileReader

func WithFileReader(fieldName, fileName string, reader any, size int64) RequestOption

WithFileReader adds a file for upload from an io.Reader.

func WithHeader

func WithHeader(key, value string) RequestOption

WithHeader sets a single header.

func WithHeaders

func WithHeaders(headers map[string]string) RequestOption

WithHeaders sets multiple headers.

func WithMaxRetries

func WithMaxRetries(maxAttempts int) RequestOption

WithMaxRetries returns a request option that sets the maximum retry attempts.

func WithProgress

func WithProgress(callback ProgressCallback) RequestOption

WithProgress sets a progress callback for file uploads.

func WithQuery

func WithQuery(key, value string) RequestOption

WithQuery sets a single query parameter.

func WithQueryParams

func WithQueryParams(params map[string]string) RequestOption

WithQueryParams sets multiple query parameters.

func WithRetry

func WithRetry(policy RetryPolicy) RequestOption

WithRetry sets the retry policy.

func WithRetryCondition

func WithRetryCondition(condition func(*models.Response, error) bool) RequestOption

WithRetryCondition returns a request option that sets a custom retry condition.

func WithRetryPolicy

func WithRetryPolicy(policy RetryPolicy) RequestOption

WithRetryPolicy returns a request option that sets the retry policy.

func WithTimeout

func WithTimeout(d time.Duration) RequestOption

WithTimeout sets the request timeout.

func WithUserAgent

func WithUserAgent(userAgent string) RequestOption

WithUserAgent sets the User-Agent header.

type Response

type Response struct {
	StatusCode int
	Status     string
	Headers    http.Header
	Cookies    []*http.Cookie
	Proto      string
	// contains filtered or unexported fields
}

Response represents an HTTP response with generic parsing capabilities.

func NewResponse

func NewResponse(resp *http.Response, finalURL string) (*Response, error)

NewResponse creates a new Response from an http.Response.

func (*Response) Bytes

func (r *Response) Bytes() []byte

Bytes returns the response body as bytes.

func (*Response) ContentType

func (r *Response) ContentType() string

ContentType returns the Content-Type header value.

func (*Response) Decode

func (r *Response) Decode(dest any, decoder codec.Decoder) error

Decode decodes the response body using the specified decoder.

func (*Response) DecodeAuto

func (r *Response) DecodeAuto(dest any) error

DecodeAuto decodes the response body based on Content-Type header.

func (*Response) DecodeJSON

func (r *Response) DecodeJSON(dest any) error

DecodeJSON decodes the response body as JSON into the destination.

func (*Response) DecodeXML

func (r *Response) DecodeXML(dest any) error

DecodeXML decodes the response body as XML into the destination.

func (*Response) GetURL

func (r *Response) GetURL() string

GetURL returns the final URL after redirects.

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError returns true if status code is 4xx.

func (*Response) IsError

func (r *Response) IsError() bool

IsError returns true if status code is 4xx or 5xx.

func (*Response) IsRedirect

func (r *Response) IsRedirect() bool

IsRedirect returns true if status code is 3xx.

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError returns true if status code is 5xx.

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if status code is 2xx.

func (*Response) Raw

func (r *Response) Raw() *http.Response

Raw returns the underlying http.Response.

func (*Response) Text

func (r *Response) Text() string

Text returns the response body as a string.

type ResponseError

type ResponseError struct {
	StatusCode int
	Status     string
	Body       []byte
	Response   *models.Response
	Err        error
}

ResponseError represents an error from the server response.

func (*ResponseError) Error

func (e *ResponseError) Error() string

Error implements the error interface.

func (*ResponseError) Is

func (e *ResponseError) Is(target error) bool

Is reports whether target matches this error.

func (*ResponseError) Unwrap

func (e *ResponseError) Unwrap() error

Unwrap returns the underlying error.

type ResponseHook

type ResponseHook func(req *Request, resp *models.Response, duration time.Duration)

ResponseHook is called after a response is received.

func ResponseLoggingHook

func ResponseLoggingHook(logger func(format string, args ...any)) ResponseHook

ResponseLoggingHook creates a response hook that logs responses.

type Result

type Result[T any] struct {
	// contains filtered or unexported fields
}

Result encapsulates both the parsed response data and response metadata. It provides a clean API that returns only 2 values (Result[T], error) instead of 3. Fields are cached at construction time for fast access in hot paths.

func DeleteJSON

func DeleteJSON[T any](rawURL string, opts ...RequestOption) (Result[T], error)

DeleteJSON performs a DELETE request and returns Result[T] with parsed JSON response.

func DeleteJSONWithContext

func DeleteJSONWithContext[T any](ctx context.Context, rawURL string, opts ...RequestOption) (Result[T], error)

DeleteJSONWithContext performs a DELETE request with context and returns Result[T].

func DoJSON

func DoJSON[T any](b *RequestBuilder) (Result[T], error)

DoJSON builds and executes the request, parsing the JSON response into Result[T].

func DoXML

func DoXML[T any](b *RequestBuilder) (Result[T], error)

DoXML builds and executes the request, parsing the XML response into Result[T].

func GetJSON

func GetJSON[T any](rawURL string, opts ...RequestOption) (Result[T], error)

============================================================================ Generic HTTP Methods - return (Result[T], error) ============================================================================ GetJSON performs a GET request and returns Result[T] with parsed JSON response.

func GetJSONWithContext

func GetJSONWithContext[T any](ctx context.Context, rawURL string, opts ...RequestOption) (Result[T], error)

GetJSONWithContext performs a GET request with context and returns Result[T].

func GetXML

func GetXML[T any](rawURL string, opts ...RequestOption) (Result[T], error)

============================================================================ Generic XML Methods - return (Result[T], error) ============================================================================ GetXML performs a GET request and returns Result[T] with parsed XML response.

func GetXMLWithContext

func GetXMLWithContext[T any](ctx context.Context, rawURL string, opts ...RequestOption) (Result[T], error)

GetXMLWithContext performs a GET request with context and returns Result[T].

func NewResult

func NewResult[T any](data T, response *models.Response) Result[T]

NewResult creates a new Result with the given data and response.

func PatchJSON

func PatchJSON[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)

PatchJSON performs a PATCH request and returns Result[T] with parsed JSON response.

func PatchJSONWithContext

func PatchJSONWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)

PatchJSONWithContext performs a PATCH request with context and returns Result[T].

func PostJSON

func PostJSON[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)

PostJSON performs a POST request and returns Result[T] with parsed JSON response.

func PostJSONWithContext

func PostJSONWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)

PostJSONWithContext performs a POST request with context and returns Result[T].

func PostXML

func PostXML[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)

PostXML performs a POST request and returns Result[T] with parsed XML response.

func PostXMLWithContext

func PostXMLWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)

PostXMLWithContext performs a POST request with context and returns Result[T].

func PutJSON

func PutJSON[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)

PutJSON performs a PUT request and returns Result[T] with parsed JSON response.

func PutJSONWithContext

func PutJSONWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)

PutJSONWithContext performs a PUT request with context and returns Result[T].

func (Result[T]) Bytes

func (r Result[T]) Bytes() []byte

Bytes returns the response body as bytes.

func (Result[T]) ContentType

func (r Result[T]) ContentType() string

ContentType returns the Content-Type header value.

func (Result[T]) Cookies

func (r Result[T]) Cookies() []*http.Cookie

Cookies returns the response cookies.

func (Result[T]) Data

func (r Result[T]) Data() T

Data returns the parsed response body as type T.

func (Result[T]) Headers

func (r Result[T]) Headers() http.Header

Headers returns the response headers.

func (Result[T]) IsClientError

func (r Result[T]) IsClientError() bool

IsClientError returns true if the status code is 4xx.

func (Result[T]) IsError

func (r Result[T]) IsError() bool

IsError returns true if the status code is 4xx or 5xx.

func (Result[T]) IsServerError

func (r Result[T]) IsServerError() bool

IsServerError returns true if the status code is 5xx.

func (Result[T]) IsSuccess

func (r Result[T]) IsSuccess() bool

IsSuccess returns true if the status code is 2xx.

func (Result[T]) Response

func (r Result[T]) Response() *models.Response

Response returns the underlying Response object.

func (Result[T]) StatusCode

func (r Result[T]) StatusCode() int

StatusCode returns the HTTP status code.

func (Result[T]) Text

func (r Result[T]) Text() string

Text returns the response body as a string.

func (Result[T]) URL

func (r Result[T]) URL() string

URL returns the final URL after redirects.

type RetryError

type RetryError struct {
	Attempts int   // Number of attempts made
	LastErr  error // The last error encountered
}

RetryError represents an error after all retries have been exhausted.

func (*RetryError) Error

func (e *RetryError) Error() string

Error implements the error interface.

func (*RetryError) Is

func (e *RetryError) Is(target error) bool

Is reports whether target matches this error.

func (*RetryError) Unwrap

func (e *RetryError) Unwrap() error

Unwrap returns the underlying error.

type RetryExecutor

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

RetryExecutor handles retry logic for HTTP requests.

func NewRetryExecutor

func NewRetryExecutor(policy RetryPolicy) *RetryExecutor

NewRetryExecutor creates a new retry executor with the given policy.

func (*RetryExecutor) Execute

func (e *RetryExecutor) Execute(ctx context.Context, fn func() (*models.Response, error)) (*models.Response, error)

Execute executes the given function with retry logic.

type RetryPolicy

type RetryPolicy struct {
	MaxAttempts     int
	InitialInterval time.Duration
	MaxInterval     time.Duration
	Multiplier      float64
	Jitter          float64
	RetryIf         func(resp *models.Response, err error) bool
}

RetryPolicy defines the retry strategy.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns a sensible default retry policy.

func ExponentialRetryPolicy

func ExponentialRetryPolicy(maxAttempts int, initialInterval, maxInterval time.Duration) RetryPolicy

ExponentialRetryPolicy returns a policy with exponential backoff.

func LinearRetryPolicy

func LinearRetryPolicy(maxAttempts int, interval time.Duration) RetryPolicy

LinearRetryPolicy returns a policy with linear backoff.

func NoRetryPolicy

func NoRetryPolicy() RetryPolicy

NoRetryPolicy returns a policy that never retries.

type Session

type Session interface {
	Client
	// Configuration methods - all return Session for chaining
	WithBaseURL(base string) Session
	WithTimeout(d time.Duration) Session
	WithProxy(proxyURL string) Session
	WithDNS(dnsServers []string) Session
	WithHeader(key, value string) Session
	WithHeaders(headers map[string]string) Session
	WithBasicAuth(username, password string) Session
	WithBearerToken(token string) Session
	WithHTTP2(enabled bool) Session
	WithKeepAlive(enabled bool) Session
	WithMaxIdleConns(n int) Session
	WithIdleTimeout(d time.Duration) Session
	WithRetry(policy RetryPolicy) Session
	WithMiddleware(m Middleware) Session
	WithCookieJar(jar http.CookieJar) Session
	// Resource management
	Close() error
	// Clear resets the session to default state
	Clear() Session
}

Session extends Client with session management capabilities.

type TimeoutError

type TimeoutError struct {
	Op       string        // Operation that timed out
	URL      string        // URL of the request
	Duration time.Duration // How long we waited
	Err      error         // Underlying error
}

TimeoutError represents a timeout error.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface.

func (*TimeoutError) Is

func (e *TimeoutError) Is(target error) bool

Is reports whether target matches this error.

func (*TimeoutError) Temporary

func (e *TimeoutError) Temporary() bool

Temporary returns true, implementing net.Error interface.

func (*TimeoutError) Timeout

func (e *TimeoutError) Timeout() bool

Timeout returns true, implementing net.Error interface.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap returns the underlying error.

Jump to

Keyboard shortcuts

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