Documentation
¶
Index ¶
- Variables
- func CloseDefaultClient() error
- func FormatBytes(bytes int64) string
- func FormatSpeed(bytesPerSecond float64) string
- func NewCookieJar() (http.CookieJar, error)
- func SetDefaultClient(client Client) error
- func ValidateConfig(cfg *Config) error
- type Client
- type Config
- type DownloadOptions
- type DownloadProgressCallback
- type DownloadResult
- type FileData
- type FormData
- type HTTPError
- type Request
- type RequestOption
- func WithAccept(accept string) RequestOption
- func WithBasicAuth(username, password string) RequestOption
- func WithBearerToken(token string) RequestOption
- func WithBinary(data []byte, contentType ...string) RequestOption
- func WithBody(body any) RequestOption
- func WithContentType(contentType string) RequestOption
- func WithContext(ctx context.Context) RequestOption
- func WithCookie(cookie *http.Cookie) RequestOption
- func WithCookieValue(name, value string) RequestOption
- func WithCookies(cookies []*http.Cookie) RequestOption
- func WithFile(fieldName, filename string, content []byte) RequestOption
- func WithForm(data map[string]string) RequestOption
- func WithFormData(data *FormData) RequestOption
- func WithHeader(key, value string) RequestOption
- func WithHeaderMap(headers map[string]string) RequestOption
- func WithJSON(data any) RequestOption
- func WithJSONAccept() RequestOption
- func WithMaxRetries(maxRetries int) RequestOption
- func WithQuery(key string, value any) RequestOption
- func WithQueryMap(params map[string]any) RequestOption
- func WithText(content string) RequestOption
- func WithTimeout(timeout time.Duration) RequestOption
- func WithUserAgent(userAgent string) RequestOption
- func WithXML(data any) RequestOption
- func WithXMLAccept() RequestOption
- type Response
- func Delete(url string, options ...RequestOption) (*Response, error)
- func Get(url string, options ...RequestOption) (*Response, error)
- func Head(url string, options ...RequestOption) (*Response, error)
- func Options(url string, options ...RequestOption) (*Response, error)
- func Patch(url string, options ...RequestOption) (*Response, error)
- func Post(url string, options ...RequestOption) (*Response, error)
- func Put(url string, options ...RequestOption) (*Response, error)
- func (r *Response) GetCookie(name string) *http.Cookie
- func (r *Response) HasCookie(name string) bool
- func (r *Response) IsClientError() bool
- func (r *Response) IsRedirect() bool
- func (r *Response) IsServerError() bool
- func (r *Response) IsSuccess() bool
- func (r *Response) JSON(v any) error
- func (r *Response) SaveToFile(filePath string) error
Constants ¶
This section is empty.
Variables ¶
var ( // ErrClientClosed is returned when attempting to use a closed client. // This occurs after calling Close() on a client instance. ErrClientClosed = errors.New("client is closed") // ErrNilConfig is returned when a nil configuration is provided. // Always provide a valid Config or use DefaultConfig(). ErrNilConfig = errors.New("config cannot be nil") // ErrInvalidURL is returned when URL validation fails. // URLs must have a valid scheme (http/https) and host. ErrInvalidURL = errors.New("invalid URL") // ErrInvalidHeader is returned when header validation fails. // Headers must not contain control characters or exceed size limits. ErrInvalidHeader = errors.New("invalid header") // ErrInvalidTimeout is returned when timeout is negative or exceeds limits. // Timeout must be between 0 and 30 minutes. ErrInvalidTimeout = errors.New("invalid timeout") // ErrInvalidRetry is returned when retry configuration is invalid. // MaxRetries must be 0-10, BackoffFactor must be 1.0-10.0. ErrInvalidRetry = errors.New("invalid retry configuration") // ErrEmptyFilePath is returned when file path is empty. // Provide a valid file path for download operations. ErrEmptyFilePath = errors.New("file path cannot be empty") // ErrFileExists is returned when file already exists and Overwrite is false. // Set Overwrite=true or ResumeDownload=true in DownloadOptions. ErrFileExists = errors.New("file already exists") // ErrResponseBodyEmpty is returned when attempting to parse empty response body. // Check response.RawBody before calling JSON() or other parsing methods. ErrResponseBodyEmpty = errors.New("response body is empty") // ErrResponseBodyTooLarge is returned when response body exceeds size limit. // Increase MaxResponseBodySize in Config or reduce response size. ErrResponseBodyTooLarge = errors.New("response body too large") )
Functions ¶
func CloseDefaultClient ¶
func CloseDefaultClient() error
CloseDefaultClient closes the default client and resets it. After calling this, the next package-level function call will create a new client. This function is safe for concurrent use.
func FormatBytes ¶
FormatBytes formats bytes in human-readable format (e.g., "1.50 KB", "2.00 MB").
func FormatSpeed ¶
FormatSpeed formats speed in human-readable format (e.g., "1.50 KB/s", "2.00 MB/s").
func NewCookieJar ¶
func SetDefaultClient ¶
SetDefaultClient sets a custom client as the default for package-level functions. The previous default client is closed automatically. Returns an error if the client is nil or not created with httpc.New().
func ValidateConfig ¶ added in v1.1.0
ValidateConfig validates the configuration with reasonable limits. Returns ErrNilConfig if cfg is nil. Returns ErrInvalidTimeout if timeout is negative or exceeds 30 minutes. Returns ErrInvalidRetry if retry configuration is invalid. Returns ErrInvalidHeader if any header is invalid.
Types ¶
type Client ¶
type Client interface {
Get(url string, options ...RequestOption) (*Response, error)
Post(url string, options ...RequestOption) (*Response, error)
Put(url string, options ...RequestOption) (*Response, error)
Patch(url string, options ...RequestOption) (*Response, error)
Delete(url string, options ...RequestOption) (*Response, error)
Head(url string, options ...RequestOption) (*Response, error)
Options(url string, options ...RequestOption) (*Response, error)
Request(ctx context.Context, method, url string, options ...RequestOption) (*Response, error)
DownloadFile(url string, filePath string, options ...RequestOption) (*DownloadResult, error)
DownloadWithOptions(url string, downloadOpts *DownloadOptions, options ...RequestOption) (*DownloadResult, error)
Close() error
}
Client represents the HTTP client interface. All methods are safe for concurrent use by multiple goroutines.
func NewMinimal ¶ added in v1.1.0
NewMinimal creates a new client with minimal features and lightweight configuration. This preset is ideal for simple, one-off requests where you don't need retries or advanced features.
func NewPerformance ¶ added in v1.1.0
NewPerformance creates a new client optimized for high-throughput scenarios. This preset uses aggressive connection pooling, longer timeouts, and faster retry intervals for maximum performance.
type Config ¶
type Config struct {
Timeout time.Duration
MaxIdleConns int
MaxConnsPerHost int
ProxyURL string
TLSConfig *tls.Config
MinTLSVersion uint16
MaxTLSVersion uint16
InsecureSkipVerify bool
MaxResponseBodySize int64
AllowPrivateIPs bool
StrictContentLength bool
MaxRetries int
RetryDelay time.Duration
BackoffFactor float64
UserAgent string
Headers map[string]string
FollowRedirects bool
EnableHTTP2 bool
EnableCookies bool
}
Config defines the HTTP client configuration.
Thread Safety: Config must be treated as immutable after passing it to New(). Do not modify Config fields after client creation. Create a new Config for each client with different settings.
func DefaultConfig ¶
func DefaultConfig() *Config
func MinimalConfig ¶ added in v1.1.0
func MinimalConfig() *Config
MinimalConfig returns a lightweight configuration with minimal features. Use this for simple, one-off requests where you don't need retries or advanced features.
func PerformanceConfig ¶ added in v1.1.0
func PerformanceConfig() *Config
func SecureConfig ¶ added in v1.1.0
func SecureConfig() *Config
func TestingConfig ¶ added in v1.1.0
func TestingConfig() *Config
TestingConfig returns a configuration optimized for testing environments. WARNING: This config disables security features and should NEVER be used in production. Use this ONLY for local development and testing with localhost/private networks.
type DownloadOptions ¶
type DownloadOptions struct {
FilePath string
ProgressCallback DownloadProgressCallback
Overwrite bool
ResumeDownload bool
}
DownloadOptions configures file download behavior.
func DefaultDownloadOptions ¶
func DefaultDownloadOptions(filePath string) *DownloadOptions
DefaultDownloadOptions creates download options with default settings. Overwrite and ResumeDownload are both false by default.
type DownloadProgressCallback ¶
DownloadProgressCallback is called during file download to report progress. Parameters: downloaded bytes, total bytes, current speed in bytes/second.
type DownloadResult ¶
type DownloadResult struct {
FilePath string
BytesWritten int64
Duration time.Duration
AverageSpeed float64
StatusCode int
ContentLength int64
Resumed bool
}
DownloadResult contains information about a completed download.
func DownloadFile ¶
func DownloadFile(url string, filePath string, options ...RequestOption) (*DownloadResult, error)
DownloadFile downloads a file from the given URL to the specified file path using the default client. Returns DownloadResult with download statistics or an error if the download fails.
func DownloadWithOptions ¶
func DownloadWithOptions(url string, downloadOpts *DownloadOptions, options ...RequestOption) (*DownloadResult, error)
DownloadWithOptions downloads a file with custom download options using the default client. Returns DownloadResult with download statistics or an error if the download fails.
type RequestOption ¶
func WithAccept ¶
func WithAccept(accept string) RequestOption
WithAccept sets the Accept header for the request.
func WithBasicAuth ¶
func WithBasicAuth(username, password string) RequestOption
WithBasicAuth adds HTTP Basic Authentication to the request. The credentials are base64-encoded and added to the Authorization header. Returns an error if username is empty or credentials contain invalid characters.
func WithBearerToken ¶
func WithBearerToken(token string) RequestOption
WithBearerToken adds a Bearer token to the Authorization header. Returns an error if token is empty, too long, or contains invalid characters.
func WithBinary ¶
func WithBinary(data []byte, contentType ...string) RequestOption
func WithBody ¶
func WithBody(body any) RequestOption
func WithContentType ¶
func WithContentType(contentType string) RequestOption
WithContentType sets the Content-Type header for the request.
func WithContext ¶
func WithContext(ctx context.Context) RequestOption
func WithCookie ¶
func WithCookie(cookie *http.Cookie) RequestOption
func WithCookieValue ¶
func WithCookieValue(name, value string) RequestOption
WithCookieValue adds a cookie with the given name and value to the request. The cookie is created with secure defaults: HttpOnly=true, SameSite=Lax. For HTTPS requests, consider using WithCookie with Secure=true. Returns an error if name is empty or contains invalid characters.
func WithCookies ¶
func WithCookies(cookies []*http.Cookie) RequestOption
func WithFile ¶
func WithFile(fieldName, filename string, content []byte) RequestOption
WithFile adds a file upload to the request. Returns an error if fieldName or filename is empty or contains invalid characters.
func WithForm ¶
func WithForm(data map[string]string) RequestOption
func WithFormData ¶
func WithFormData(data *FormData) RequestOption
func WithHeader ¶
func WithHeader(key, value string) RequestOption
WithHeader adds a custom header to the request. Returns an error if the header key or value is invalid.
func WithHeaderMap ¶
func WithHeaderMap(headers map[string]string) RequestOption
WithHeaderMap adds multiple headers to the request. Returns an error if any header key or value is invalid.
func WithJSON ¶
func WithJSON(data any) RequestOption
WithJSON sets the request body to JSON-encoded data and sets Content-Type to application/json.
func WithJSONAccept ¶
func WithJSONAccept() RequestOption
WithJSONAccept sets the Accept header to application/json.
func WithMaxRetries ¶
func WithMaxRetries(maxRetries int) RequestOption
WithMaxRetries sets the maximum number of retry attempts. Returns ErrInvalidRetry if maxRetries is not between 0 and 10.
func WithQuery ¶
func WithQuery(key string, value any) RequestOption
WithQuery adds a single query parameter to the request URL. Returns an error if key is empty, too long, or contains invalid characters.
func WithQueryMap ¶
func WithQueryMap(params map[string]any) RequestOption
WithQueryMap adds multiple query parameters to the request URL. Returns an error if any key is empty, too long, or contains invalid characters.
func WithText ¶
func WithText(content string) RequestOption
func WithTimeout ¶
func WithTimeout(timeout time.Duration) RequestOption
WithTimeout sets the request timeout. Returns ErrInvalidTimeout if timeout is negative or exceeds 30 minutes.
func WithUserAgent ¶
func WithUserAgent(userAgent string) RequestOption
WithUserAgent sets the User-Agent header for the request.
func WithXML ¶
func WithXML(data any) RequestOption
WithXML sets the request body to XML-encoded data and sets Content-Type to application/xml.
func WithXMLAccept ¶
func WithXMLAccept() RequestOption
WithXMLAccept sets the Accept header to application/xml.
type Response ¶
type Response struct {
StatusCode int
Status string
Headers http.Header
Body string
RawBody []byte
ContentLength int64
Duration time.Duration
Attempts int
Cookies []*http.Cookie
}
Response represents an HTTP response.
Thread Safety: Response objects are immutable after creation and safe to read from multiple goroutines concurrently. All methods are goroutine-safe. Do not modify Response fields directly.
func Delete ¶
func Delete(url string, options ...RequestOption) (*Response, error)
Delete executes a DELETE request using the default client
func Get ¶
func Get(url string, options ...RequestOption) (*Response, error)
Get executes a GET request using the default client
func Head ¶
func Head(url string, options ...RequestOption) (*Response, error)
Head executes a HEAD request using the default client
func Options ¶
func Options(url string, options ...RequestOption) (*Response, error)
Options executes an OPTIONS request using the default client
func Patch ¶
func Patch(url string, options ...RequestOption) (*Response, error)
Patch executes a PATCH request using the default client
func Post ¶
func Post(url string, options ...RequestOption) (*Response, error)
Post executes a POST request using the default client
func Put ¶
func Put(url string, options ...RequestOption) (*Response, error)
Put executes a PUT request using the default client
func (*Response) IsClientError ¶
IsClientError returns true if the response status code indicates a client error (4xx)
func (*Response) IsRedirect ¶
IsRedirect returns true if the response status code indicates a redirect (3xx)
func (*Response) IsServerError ¶
IsServerError returns true if the response status code indicates a server error (5xx)
func (*Response) IsSuccess ¶
IsSuccess returns true if the response status code indicates success (2xx)
func (*Response) JSON ¶
JSON unmarshals the response body into the provided interface. Returns ErrResponseBodyEmpty if the body is nil or empty. Returns ErrResponseBodyTooLarge if the body exceeds 50MB.