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 ¶
- Variables
- func CombineRetryConditions(conditions ...func(*models.Response, error) bool) func(*models.Response, error) bool
- func CreateMockResponse(statusCode int, body []byte, headers http.Header) *models.Response
- func Decode[T any](r *Response, decoder codec.Decoder) (T, error)
- func DecodeAuto[T any](r *Response) (T, error)
- func DefaultRetryCondition(resp *models.Response, err error) bool
- func Delete(rawURL string, opts ...RequestOption) (*models.Response, error)
- func DeleteWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)
- func Get(rawURL string, opts ...RequestOption) (*models.Response, error)
- func GetBytes(rawURL string, opts ...RequestOption) ([]byte, error)
- func GetString(rawURL string, opts ...RequestOption) (string, error)
- func GetWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)
- func Head(rawURL string, opts ...RequestOption) (*models.Response, error)
- func HeadWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)
- func IsConnectionError(err error) bool
- func IsResponseError(err error) bool
- func IsTemporary(err error) bool
- func IsTimeout(err error) bool
- func JSON[T any](r *Response) (T, error)
- func MustJSON[T any](r *Response) T
- func MustXML[T any](r *Response) T
- func Options(rawURL string, opts ...RequestOption) (*models.Response, error)
- func OptionsWithContext(ctx context.Context, rawURL string, opts ...RequestOption) (*models.Response, error)
- func Patch(rawURL string, body any, opts ...RequestOption) (*models.Response, error)
- func PatchWithContext(ctx context.Context, rawURL string, body any, opts ...RequestOption) (*models.Response, error)
- func Post(rawURL string, body any, opts ...RequestOption) (*models.Response, error)
- func PostWithContext(ctx context.Context, rawURL string, body any, opts ...RequestOption) (*models.Response, error)
- func PrepareBody(body any) (io.Reader, string, error)
- func Put(rawURL string, body any, opts ...RequestOption) (*models.Response, error)
- func PutWithContext(ctx context.Context, rawURL string, body any, opts ...RequestOption) (*models.Response, error)
- func ReleaseBuilder(b *RequestBuilder)
- func ReleaseConfig(c *RequestConfig)
- func RetryOn5xx(resp *models.Response, err error) bool
- func RetryOnNetworkError(resp *models.Response, err error) bool
- func RetryOnStatusCodes(codes ...int) func(*models.Response, error) bool
- func SetDefaultClient(client HTTPClient)
- func XML[T any](r *Response) (T, error)
- type BasicAuth
- type Client
- type ConnectionError
- type DecodeError
- type EncodeError
- type ErrorHook
- type FileUpload
- type FileUploadConfig
- type HTTPClient
- type Handler
- type Hooks
- func (h *Hooks) Clear() *Hooks
- func (h *Hooks) Clone() *Hooks
- func (h *Hooks) Len() int
- func (h *Hooks) OnError(hook ErrorHook) *Hooks
- func (h *Hooks) OnRequest(hook RequestHook) *Hooks
- func (h *Hooks) OnResponse(hook ResponseHook) *Hooks
- func (h *Hooks) TriggerError(req *Request, err error, duration time.Duration)
- func (h *Hooks) TriggerRequest(req *Request)
- func (h *Hooks) TriggerResponse(req *Request, resp *models.Response, duration time.Duration)
- type Method
- type MetricsHook
- type Middleware
- func AuthMiddleware(authHeader string) Middleware
- func BasicAuthMiddleware(username, password string) Middleware
- func BearerTokenMiddleware(token string) Middleware
- func ChainMiddleware(middlewares ...Middleware) Middleware
- func ConditionalMiddleware(condition func(*Request) bool, m Middleware) Middleware
- func HeaderMiddleware(headers map[string]string) Middleware
- func HooksMiddleware(hooks *Hooks) Middleware
- func LoggingMiddleware(logger func(format string, args ...any)) Middleware
- func RecoveryMiddleware(onPanic func(req *Request, recovered any)) Middleware
- func RetryMiddleware(policy RetryPolicy) Middleware
- func UserAgentMiddleware(userAgent string) Middleware
- type MiddlewareChain
- func (c *MiddlewareChain) Clone() *MiddlewareChain
- func (c *MiddlewareChain) Execute(req *Request, finalHandler Handler) (*models.Response, error)
- func (c *MiddlewareChain) Len() int
- func (c *MiddlewareChain) Use(m Middleware) *MiddlewareChain
- func (c *MiddlewareChain) UseFunc(fn func(req *Request, next Handler) (*models.Response, error)) *MiddlewareChain
- type MiddlewareFunc
- type ProgressCallback
- type Request
- type RequestBuilder
- func AcquireBuilder(method Method, rawURL string) *RequestBuilder
- func NewDelete(rawURL string) *RequestBuilder
- func NewDeleteRequest(rawURL string) *RequestBuilder
- func NewGet(rawURL string) *RequestBuilder
- func NewGetRequest(rawURL string) *RequestBuilder
- func NewPatch(rawURL string) *RequestBuilder
- func NewPatchRequest(rawURL string) *RequestBuilder
- func NewPost(rawURL string) *RequestBuilder
- func NewPostRequest(rawURL string) *RequestBuilder
- func NewPut(rawURL string) *RequestBuilder
- func NewPutRequest(rawURL string) *RequestBuilder
- func NewRequest(method Method, rawURL string) *RequestBuilder
- func (b *RequestBuilder) Build() (*Request, error)
- func (b *RequestBuilder) BuildCopy() (*Request, error)
- func (b *RequestBuilder) Clone() *RequestBuilder
- func (b *RequestBuilder) Do() (*models.Response, error)
- func (b *RequestBuilder) GetBodyBytes() []byte
- func (b *RequestBuilder) GetFiles() []FileUpload
- func (b *RequestBuilder) GetForm() url.Values
- func (b *RequestBuilder) GetHeaders() http.Header
- func (b *RequestBuilder) GetMethod() Method
- func (b *RequestBuilder) GetQuery() url.Values
- func (b *RequestBuilder) GetTimeout() time.Duration
- func (b *RequestBuilder) GetURL() string
- func (b *RequestBuilder) Reset()
- func (b *RequestBuilder) WithBasicAuth(username, password string) *RequestBuilder
- func (b *RequestBuilder) WithBearerToken(token string) *RequestBuilder
- func (b *RequestBuilder) WithBody(body io.Reader) *RequestBuilder
- func (b *RequestBuilder) WithBodyBytes(data []byte) *RequestBuilder
- func (b *RequestBuilder) WithContext(ctx context.Context) *RequestBuilder
- func (b *RequestBuilder) WithEncoder(encoder codec.Encoder, data any) *RequestBuilder
- func (b *RequestBuilder) WithFile(fieldName, fileName string, reader io.Reader) *RequestBuilder
- func (b *RequestBuilder) WithForm(data map[string]string) *RequestBuilder
- func (b *RequestBuilder) WithFormValues(values url.Values) *RequestBuilder
- func (b *RequestBuilder) WithHeader(key, value string) *RequestBuilder
- func (b *RequestBuilder) WithHeaders(headers map[string]string) *RequestBuilder
- func (b *RequestBuilder) WithJSON(data any) *RequestBuilder
- func (b *RequestBuilder) WithMethod(method Method) *RequestBuilder
- func (b *RequestBuilder) WithQuery(key, value string) *RequestBuilder
- func (b *RequestBuilder) WithQueryParams(params map[string]string) *RequestBuilder
- func (b *RequestBuilder) WithTimeout(d time.Duration) *RequestBuilder
- func (b *RequestBuilder) WithURL(rawURL string) *RequestBuilder
- func (b *RequestBuilder) WithXML(data any) *RequestBuilder
- type RequestConfig
- type RequestError
- type RequestHook
- type RequestOption
- func WithAccept(accept string) RequestOption
- func WithBasicAuth(username, password string) RequestOption
- func WithBearerToken(token string) RequestOption
- func WithContentType(contentType string) RequestOption
- func WithContext(ctx context.Context) RequestOption
- func WithFile(fieldName, filePath string) RequestOption
- func WithFileReader(fieldName, fileName string, reader any, size int64) RequestOption
- func WithHeader(key, value string) RequestOption
- func WithHeaders(headers map[string]string) RequestOption
- func WithMaxRetries(maxAttempts int) RequestOption
- func WithProgress(callback ProgressCallback) RequestOption
- func WithQuery(key, value string) RequestOption
- func WithQueryParams(params map[string]string) RequestOption
- func WithRetry(policy RetryPolicy) RequestOption
- func WithRetryCondition(condition func(*models.Response, error) bool) RequestOption
- func WithRetryPolicy(policy RetryPolicy) RequestOption
- func WithTimeout(d time.Duration) RequestOption
- func WithUserAgent(userAgent string) RequestOption
- type Response
- func (r *Response) Bytes() []byte
- func (r *Response) ContentType() string
- func (r *Response) Decode(dest any, decoder codec.Decoder) error
- func (r *Response) DecodeAuto(dest any) error
- func (r *Response) DecodeJSON(dest any) error
- func (r *Response) DecodeXML(dest any) error
- func (r *Response) GetURL() string
- func (r *Response) IsClientError() bool
- func (r *Response) IsError() bool
- func (r *Response) IsRedirect() bool
- func (r *Response) IsServerError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) Raw() *http.Response
- func (r *Response) Text() string
- type ResponseError
- type ResponseHook
- type Result
- func DeleteJSON[T any](rawURL string, opts ...RequestOption) (Result[T], error)
- func DeleteJSONWithContext[T any](ctx context.Context, rawURL string, opts ...RequestOption) (Result[T], error)
- func DoJSON[T any](b *RequestBuilder) (Result[T], error)
- func DoXML[T any](b *RequestBuilder) (Result[T], error)
- func GetJSON[T any](rawURL string, opts ...RequestOption) (Result[T], error)
- func GetJSONWithContext[T any](ctx context.Context, rawURL string, opts ...RequestOption) (Result[T], error)
- func GetXML[T any](rawURL string, opts ...RequestOption) (Result[T], error)
- func GetXMLWithContext[T any](ctx context.Context, rawURL string, opts ...RequestOption) (Result[T], error)
- func NewResult[T any](data T, response *models.Response) Result[T]
- func PatchJSON[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func PatchJSONWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func PostJSON[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func PostJSONWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func PostXML[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func PostXMLWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func PutJSON[T any](rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func PutJSONWithContext[T any](ctx context.Context, rawURL string, body any, opts ...RequestOption) (Result[T], error)
- func (r Result[T]) Bytes() []byte
- func (r Result[T]) ContentType() string
- func (r Result[T]) Cookies() []*http.Cookie
- func (r Result[T]) Data() T
- func (r Result[T]) Headers() http.Header
- func (r Result[T]) IsClientError() bool
- func (r Result[T]) IsError() bool
- func (r Result[T]) IsServerError() bool
- func (r Result[T]) IsSuccess() bool
- func (r Result[T]) Response() *models.Response
- func (r Result[T]) StatusCode() int
- func (r Result[T]) Text() string
- func (r Result[T]) URL() string
- type RetryError
- type RetryExecutor
- type RetryPolicy
- type Session
- type TimeoutError
Constants ¶
This section is empty.
Variables ¶
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 ¶
CreateMockResponse creates a models.Response for testing purposes.
func DecodeAuto ¶
DecodeAuto is a generic function that parses based on Content-Type.
func DefaultRetryCondition ¶
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 ¶
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 ¶
IsConnectionError checks if an error is a connection error.
func IsResponseError ¶
IsResponseError checks if an error is a response error.
func IsTemporary ¶
IsTemporary checks if an error is temporary and can be retried.
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 PatchWithContext ¶
func PatchWithContext(ctx context.Context, rawURL string, body any, opts ...RequestOption) (*models.Response, error)
PatchWithContext performs a PATCH request with context.
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 ¶
PrepareBody converts the body to an io.Reader and returns the content type. This is exported for use by the main package.
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 ¶
RetryOn5xx returns a retry condition that retries on 5xx errors.
func RetryOnNetworkError ¶
RetryOnNetworkError returns a retry condition that only retries on network errors.
func RetryOnStatusCodes ¶
RetryOnStatusCodes returns a retry condition that retries on specific status codes.
func SetDefaultClient ¶
func SetDefaultClient(client HTTPClient)
SetDefaultClient sets the default HTTP client.
Types ¶
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 ¶
ErrorHook is called when an error occurs.
func ErrorLoggingHook ¶
ErrorLoggingHook creates an error hook that logs errors.
type FileUpload ¶
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 ¶
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 Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
Hooks manages request/response hooks using atomic operations for better performance.
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 ¶
TriggerError calls all registered error hooks (lock-free).
func (*Hooks) TriggerRequest ¶
TriggerRequest calls all registered request 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 ¶
HasRequestBody returns true if the method typically has a request body.
func (Method) IsIdempotent ¶
IsIdempotent returns true if the method is idempotent.
type MetricsHook ¶
type MetricsHook struct {
// contains filtered or unexported fields
}
MetricsHook creates hooks for collecting metrics using atomic operations.
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) ResponseHook ¶
func (m *MetricsHook) ResponseHook() ResponseHook
ResponseHook returns a response hook for counting responses.
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 ¶
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 ¶
func (c *MiddlewareChain) Use(m Middleware) *MiddlewareChain
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 ¶
MiddlewareFunc is a function adapter for 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 ¶
AddHeader adds a header value to the request. Multiple values can be added for the same 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) 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 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 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 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 ¶
NewResponse creates a new Response from an http.Response.
func (*Response) ContentType ¶
ContentType returns the Content-Type header value.
func (*Response) DecodeAuto ¶
DecodeAuto decodes the response body based on Content-Type header.
func (*Response) DecodeJSON ¶
DecodeJSON decodes the response body as JSON into the destination.
func (*Response) IsClientError ¶
IsClientError returns true if status code is 4xx.
func (*Response) IsRedirect ¶
IsRedirect returns true if status code is 3xx.
func (*Response) IsServerError ¶
IsServerError returns true if status code is 5xx.
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 ¶
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 PatchJSON ¶
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 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 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 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]) ContentType ¶
ContentType returns the Content-Type header value.
func (Result[T]) Data ¶
func (r Result[T]) Data() T
Data returns the parsed response body as type T.
func (Result[T]) IsClientError ¶
IsClientError returns true if the status code is 4xx.
func (Result[T]) IsServerError ¶
IsServerError returns true if the status code is 5xx.
func (Result[T]) StatusCode ¶
StatusCode returns the HTTP status code.
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.
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.