Documentation
¶
Index ¶
- type Client
- func (c *Client) Do(ctx context.Context, opts ...RequestOption) (*Response, error)
- func (c *Client) Request(ctx context.Context, opts ...RequestOption) ([]byte, error)
- func (c *Client) WebSocketStream(ctx context.Context, sendChan <-chan interface{}, ...) error
- func (c *Client) WebSocketStreamWithReconnect(ctx context.Context, sendChan <-chan interface{}, ...) error
- func (c *Client) WithLogger(logger Logger) *Client
- type ErrorHook
- type HTTPError
- type Logger
- type RequestHook
- type RequestOption
- func DELETE(path string) RequestOption
- func GET(path string) RequestOption
- func HEAD(path string) RequestOption
- func OPTIONS(path string) RequestOption
- func PATCH(path string) RequestOption
- func POST(path string) RequestOption
- func PUT(path string) RequestOption
- func WithAfterResponse(hook ResponseHook) RequestOption
- func WithAuth(token string) RequestOption
- func WithBasicAuth(username, password string) RequestOption
- func WithBearerToken(token string) RequestOption
- func WithBeforeRequest(hook RequestHook) RequestOption
- func WithBody(body interface{}) RequestOption
- func WithDefaultRetry() RequestOption
- func WithDefaultWebSocketReconnect() RequestOption
- func WithFile(formFieldName string, file *multipart.FileHeader) RequestOption
- func WithForm(key, value string) RequestOption
- func WithHeader(key, value string) RequestOption
- func WithInsecureSkipVerify() RequestOption
- func WithJSON(body interface{}) RequestOption
- func WithMethod(method string) RequestOption
- func WithOnError(hook ErrorHook) RequestOption
- func WithPath(path string) RequestOption
- func WithQueryParam(key, value string) RequestOption
- func WithQueryParams(params url.Values) RequestOption
- func WithRetry(config RetryConfig) RequestOption
- func WithWebSocketAutoReconnect(config WebSocketConfig) RequestOption
- type Requests
- type Response
- type ResponseHook
- type RetryConfig
- type WebSocketConfig
- type WebSocketError
- type WebSocketResponse
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents an HTTP/WebSocket client for making requests.
func NewClient ¶
NewClient creates a new HTTP client with the specified base URL and timeout.
The baseURL should not include a trailing slash. All request paths will be appended to this base URL.
Example:
client := reqws.NewClient("https://api.example.com", 30*time.Second)
body, err := client.Request(ctx, reqws.GET("/users"))
func NewRequests ¶
NewRequests is deprecated. Use NewClient instead. Kept for backward compatibility.
func (*Client) Do ¶
Do executes an HTTP request and returns the full Response object with body, headers, and status code. This method gives you full control - it does NOT automatically fail on non-2xx status codes.
Use this when you need: - Access to response headers - Manual handling of different status codes - Response helper methods (JSON, IsSuccess, etc.)
Unlike Request(), this does not return an error for non-2xx status codes. You must manually check resp.IsSuccess() or resp.StatusCode. Supports retry via WithRetry() or WithDefaultRetry() options.
Example:
resp, err := client.Do(ctx,
reqws.GET("/users/1"),
reqws.WithBearerToken("token"),
)
if err != nil {
return err
}
if !resp.IsSuccess() {
return fmt.Errorf("failed: %d", resp.StatusCode)
}
var user User
resp.JSON(&user)
func (*Client) Request ¶
Request executes an HTTP request and returns only the response body as bytes. This is the simple method for most use cases - it automatically fails on non-2xx status codes.
Returns an error if the status code is not 2xx. Supports retry via WithRetry() or WithDefaultRetry() options.
Example:
body, err := client.Request(ctx,
reqws.GET("/users/1"),
reqws.WithBearerToken("token"),
)
func (*Client) WebSocketStream ¶
func (c *Client) WebSocketStream(ctx context.Context, sendChan <-chan interface{}, receiveChan chan<- WebSocketResponse, opts ...RequestOption) error
WebSocketStream - Persistent connection with channel-based communication
func (*Client) WebSocketStreamWithReconnect ¶
func (c *Client) WebSocketStreamWithReconnect(ctx context.Context, sendChan <-chan interface{}, receiveChan chan<- WebSocketResponse, opts ...RequestOption) error
WebSocketStreamWithReconnect wraps WebSocketStream with automatic reconnection logic. If the connection drops, it will automatically attempt to reconnect with exponential backoff. Use WithWebSocketAutoReconnect() or WithDefaultWebSocketReconnect() to configure reconnection behavior.
func (*Client) WithLogger ¶
WithLogger sets a custom logger for the Client. The logger will be used for all HTTP and WebSocket operations. If no logger is provided, logging is disabled by default.
Example:
client := reqws.NewClient("https://api.example.com", 30*time.Second).
WithLogger(myLogger)
type ErrorHook ¶
ErrorHook is a function that runs when an error occurs during the request. It receives the original request and the error that occurred. This hook cannot modify the error, it's primarily for logging/monitoring.
type HTTPError ¶
HTTPError represents an HTTP error response with a non-2xx status code.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError with the given status code and response body.
type Logger ¶
type Logger interface {
Debug(msg string, keysAndValues ...interface{})
Info(msg string, keysAndValues ...interface{})
Error(msg string, keysAndValues ...interface{})
}
Logger is an interface for logging operations. Users can provide their own implementation (slog, zap, logrus, etc.)
type RequestHook ¶
RequestHook is a function that runs before a request is sent. It receives the prepared http.Request and can modify it or return an error to abort the request.
type RequestOption ¶
type RequestOption func(*requestConfig)
func DELETE ¶
func DELETE(path string) RequestOption
DELETE creates a DELETE request to the specified path. This is a shortcut for WithMethod("DELETE") + WithPath(path).
Example:
client.Request(ctx, reqws.DELETE("/users/1"))
func GET ¶
func GET(path string) RequestOption
GET creates a GET request to the specified path. This is a shortcut for WithMethod("GET") + WithPath(path).
Example:
body, err := client.Request(ctx, reqws.GET("/users"))
resp, err := client.Do(ctx, reqws.GET("/users"))
func HEAD ¶
func HEAD(path string) RequestOption
HEAD creates a HEAD request to the specified path. Useful for checking if a resource exists without downloading it.
Example:
resp, err := client.Do(ctx, reqws.HEAD("/users/1"))
func OPTIONS ¶
func OPTIONS(path string) RequestOption
OPTIONS creates an OPTIONS request to the specified path. Useful for CORS preflight requests.
Example:
resp, err := client.Do(ctx, reqws.OPTIONS("/api"))
func PATCH ¶
func PATCH(path string) RequestOption
PATCH creates a PATCH request to the specified path. This is a shortcut for WithMethod("PATCH") + WithPath(path).
Example:
client.Do(ctx, reqws.PATCH("/users/1"), reqws.WithJSON(updates))
func POST ¶
func POST(path string) RequestOption
POST creates a POST request to the specified path. This is a shortcut for WithMethod("POST") + WithPath(path).
Example:
client.Do(ctx, reqws.POST("/users"), reqws.WithJSON(user))
func PUT ¶
func PUT(path string) RequestOption
PUT creates a PUT request to the specified path. This is a shortcut for WithMethod("PUT") + WithPath(path).
Example:
client.Do(ctx, reqws.PUT("/users/1"), reqws.WithJSON(user))
func WithAfterResponse ¶
func WithAfterResponse(hook ResponseHook) RequestOption
WithAfterResponse adds a hook that runs after receiving the HTTP response. Multiple hooks can be added and will be executed in the order they were added. If any hook returns an error, the response is treated as failed.
Use cases: - Log response details - Record metrics (latency, status codes) - Validate response structure - Custom retry logic based on response
func WithAuth ¶
func WithAuth(token string) RequestOption
WithAuth sets the Authorization header with the provided token. The token should include the auth scheme (e.g., "Bearer xxx").
For Bearer tokens specifically, consider using WithBearerToken() instead.
Example:
client.Request(ctx, reqws.GET("/protected"), reqws.WithAuth("Bearer abc123"))
func WithBasicAuth ¶
func WithBasicAuth(username, password string) RequestOption
WithBasicAuth sets the Authorization header with Basic authentication. The credentials will be automatically base64 encoded.
Example:
client.Request(ctx,
reqws.GET("/protected"),
reqws.WithBasicAuth("username", "password"),
)
func WithBearerToken ¶
func WithBearerToken(token string) RequestOption
WithBearerToken sets the Authorization header with a Bearer token. This is a convenience method that automatically prepends "Bearer " to the token.
Example:
client.Request(ctx,
reqws.GET("/protected"),
reqws.WithBearerToken("abc123"),
)
func WithBeforeRequest ¶
func WithBeforeRequest(hook RequestHook) RequestOption
WithBeforeRequest adds a hook that runs before the HTTP request is sent. Multiple hooks can be added and will be executed in the order they were added. If any hook returns an error, the request is aborted.
Use cases: - Add custom headers - Log request details - Modify request body - Add authentication tokens dynamically
func WithBody ¶
func WithBody(body interface{}) RequestOption
WithBody sets the request body. The body will be automatically marshaled to JSON.
For more explicit JSON handling, consider using WithJSON() instead.
Example:
client.Do(ctx, reqws.POST("/users"), reqws.WithBody(user))
func WithDefaultRetry ¶
func WithDefaultRetry() RequestOption
WithDefaultRetry enables retry with default configuration. - MaxRetries: 3 - InitialDelay: 100ms - MaxDelay: 5s - Multiplier: 2.0 (exponential backoff)
func WithDefaultWebSocketReconnect ¶
func WithDefaultWebSocketReconnect() RequestOption
WithDefaultWebSocketReconnect enables WebSocket auto-reconnection with default configuration. - MaxReconnectAttempts: 10 - ReconnectDelay: 1s - MaxReconnectDelay: 30s - ReconnectMultiplier: 2.0 (exponential backoff)
func WithFile ¶
func WithFile(formFieldName string, file *multipart.FileHeader) RequestOption
WithFile adds a file to the request for multipart/form-data upload. The formFieldName is the name of the form field (defaults to "file" if empty).
Example:
client.Do(ctx,
reqws.POST("/upload"),
reqws.WithFile("avatar", fileHeader),
)
func WithForm ¶
func WithForm(key, value string) RequestOption
WithForm adds a form field for multipart/form-data requests. Use this together with WithFile() for file uploads.
Example:
client.Do(ctx,
reqws.POST("/upload"),
reqws.WithFile("avatar", fileHeader),
reqws.WithForm("user_id", "123"),
reqws.WithForm("description", "Profile picture"),
)
func WithHeader ¶
func WithHeader(key, value string) RequestOption
WithHeader adds a custom HTTP header to the request. Can be called multiple times to add multiple headers.
Example:
client.Request(ctx,
reqws.GET("/api/data"),
reqws.WithHeader("X-API-Version", "v1"),
reqws.WithHeader("X-Request-ID", "12345"),
)
func WithInsecureSkipVerify ¶
func WithInsecureSkipVerify() RequestOption
WithInsecureSkipVerify disables TLS certificate verification. WARNING: This should only be used for testing or development. Using this in production makes your application vulnerable to man-in-the-middle attacks.
func WithJSON ¶
func WithJSON(body interface{}) RequestOption
WithJSON sets the request body as JSON. This is an explicit alias for WithBody() for better code clarity. The body will be marshaled to JSON automatically.
Example:
client.Do(ctx,
reqws.POST("/users"),
reqws.WithJSON(map[string]string{
"name": "John Doe",
"email": "john@example.com",
}),
)
func WithMethod ¶
func WithMethod(method string) RequestOption
WithMethod sets a custom HTTP method for the request. For common methods (GET, POST, PUT, DELETE, PATCH), consider using the shortcut functions instead.
Use this for custom or less common HTTP methods like PROPFIND, MKCOL, etc.
Example:
client.Do(ctx, reqws.WithMethod("PROPFIND"), reqws.WithPath("/files"))
func WithOnError ¶
func WithOnError(hook ErrorHook) RequestOption
WithOnError adds a hook that runs when an error occurs. Multiple hooks can be added and will be executed in the order they were added. These hooks cannot modify the error, they're for observability.
Use cases: - Log errors - Send error alerts - Record error metrics - Trace error propagation
func WithPath ¶
func WithPath(path string) RequestOption
WithPath sets the request path. The path is automatically prefixed with "/" if not present.
Note: For common cases, consider using HTTP method shortcuts (GET, POST, etc.) which combine method and path.
Example:
// Legacy approach
client.Request(ctx, reqws.WithMethod("GET"), reqws.WithPath("/users"))
// Better: use shortcut instead
client.Request(ctx, reqws.GET("/users"))
func WithQueryParam ¶
func WithQueryParam(key, value string) RequestOption
WithQueryParam adds a single query parameter to the request URL. Can be called multiple times to add multiple parameters.
Example:
client.Request(ctx,
reqws.GET("/users"),
reqws.WithQueryParam("status", "active"),
reqws.WithQueryParam("limit", "10"),
)
func WithQueryParams ¶
func WithQueryParams(params url.Values) RequestOption
WithQueryParams adds multiple query parameters at once from url.Values. For adding single parameters, use WithQueryParam() instead.
Example:
params := url.Values{}
params.Add("status", "active")
params.Add("limit", "10")
client.Request(ctx, reqws.GET("/users"), reqws.WithQueryParams(params))
func WithRetry ¶
func WithRetry(config RetryConfig) RequestOption
WithRetry enables retry with custom configuration.
func WithWebSocketAutoReconnect ¶
func WithWebSocketAutoReconnect(config WebSocketConfig) RequestOption
WithWebSocketAutoReconnect enables WebSocket auto-reconnection with custom configuration.
type Requests ¶
type Requests = Client
Requests is deprecated. Use Client instead. Kept for backward compatibility.
type Response ¶
Response represents an HTTP response with helper methods.
func (*Response) IsClientError ¶
IsClientError returns true if the status code is 4xx (400-499).
func (*Response) IsServerError ¶
IsServerError returns true if the status code is 5xx (500-599).
type ResponseHook ¶
ResponseHook is a function that runs after a response is received. It receives both the original request and the response. Return an error to treat the response as failed.
type RetryConfig ¶
type RetryConfig struct {
MaxRetries int // Maximum number of retry attempts (default: 3)
InitialDelay time.Duration // Initial delay before first retry (default: 100ms)
MaxDelay time.Duration // Maximum delay between retries (default: 5s)
Multiplier float64 // Backoff multiplier (default: 2.0)
}
RetryConfig defines the configuration for retry behavior.
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns a sensible default retry configuration.
type WebSocketConfig ¶
type WebSocketConfig struct {
AutoReconnect bool // Enable automatic reconnection on disconnect
MaxReconnectAttempts int // Maximum number of reconnection attempts (0 = infinite)
ReconnectDelay time.Duration // Initial delay before reconnection
MaxReconnectDelay time.Duration // Maximum delay between reconnections
ReconnectMultiplier float64 // Backoff multiplier for reconnection delay
OnReconnect func() // Callback function called on each reconnection attempt
}
WebSocketConfig defines configuration for WebSocket connections.
func DefaultWebSocketConfig ¶
func DefaultWebSocketConfig() WebSocketConfig
DefaultWebSocketConfig returns a sensible default WebSocket configuration.
type WebSocketError ¶
WebSocketError represents a WebSocket-specific error.
func NewWebSocketError ¶
func NewWebSocketError(reason string, err error) *WebSocketError
NewWebSocketError creates a new WebSocketError with the given reason and underlying error.
func (*WebSocketError) Error ¶
func (e *WebSocketError) Error() string
func (*WebSocketError) Unwrap ¶
func (e *WebSocketError) Unwrap() error
Unwrap returns the underlying error for error chain support.
type WebSocketResponse ¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
http_advanced
command
|
|
|
websocket_advanced
command
|
|
|
websocket_basic
command
|