Documentation
¶
Index ¶
- func CacheMiddleware(cfg *CacheConfig) func(next http.RoundTripper) http.RoundTripper
- func NewCircuitBreakerMiddleware(name string) func(next http.RoundTripper) http.RoundTripper
- func NewHeaderMiddleware(headers map[string]string) func(next http.RoundTripper) http.RoundTripper
- func NewLoggingMiddleware(name string) func(next http.RoundTripper) http.RoundTripper
- type CacheConfig
- type CachePolicy
- type HTTPClient
- func (c *HTTPClient) Delete(ctx context.Context, path string) (*HTTPResponse, error)
- func (c *HTTPClient) Get(ctx context.Context, path string) (*HTTPResponse, error)
- func (c *HTTPClient) Head(ctx context.Context, path string) (*HTTPResponse, error)
- func (c *HTTPClient) Patch(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)
- func (c *HTTPClient) Post(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)
- func (c *HTTPClient) Put(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)
- type HTTPResponse
- type HTTPStatusError
- type IRedisClient
- type RoundTripperFunc
- type RoundTripperMiddleware
- type SerializableCache
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CacheMiddleware ¶
func CacheMiddleware(cfg *CacheConfig) func(next http.RoundTripper) http.RoundTripper
CacheMiddleware is an HTTP middleware that provides transparent caching for GET requests using a Redis backend.
It checks if the cache is enabled and a Redis client is configured. For each GET request, it attempts to retrieve a cached response from Redis using a generated cache key. If a valid cached response is found, it is deserialized and returned immediately, setting the "X-Cache" header to "HIT". If not found, the request proceeds to the next RoundTripper, and the response is cached asynchronously if the status code is 2xx. The cache TTL can be overridden by configuration, and the middleware also updates the "Cache-Control" header accordingly.
Parameters:
cfg *CacheConfig: Cache configuration struct. - RedisClient: Redis client used to store and retrieve cached data. - TTL: Default expiration time (Time To Live) for cache entries. - OverrideTTL: If true, overrides the TTL from the Cache-Control header with the configured TTL. - Headers: HTTP headers that will be considered when generating the cache key.
Returns:
A function that wraps an http.RoundTripper with caching logic.
func NewCircuitBreakerMiddleware ¶
func NewCircuitBreakerMiddleware(name string) func(next http.RoundTripper) http.RoundTripper
NewCircuitBreaker wraps an http.RoundTripper with a circuit breaker using gobreaker.
The circuit breaker monitors HTTP requests and opens the circuit when the error rate reaches a threshold (default: 50% errors out of at least 20 requests, considering status >= 500 or 429 as errors). While open, requests will fail fast without calling the underlying transport. After a short interval, a limited number of requests are allowed to test recovery. If successful, the circuit closes again.
Parameters:
cfg: Configuration for the circuit breaker.
- cfg.Enabled: activates/deactivates the breaker.
- cfg.Name: identifies the breaker instance (useful for logging/metrics).
next: The next http.RoundTripper to be wrapped. This is usually http.DefaultTransport or a custom transport.
Returns:
An http.RoundTripper that applies circuit breaker logic to all requests.
func NewHeaderMiddleware ¶
func NewHeaderMiddleware(headers map[string]string) func(next http.RoundTripper) http.RoundTripper
NewHeaderMiddleware returns an HTTP middleware that adds custom headers to all outgoing requests.
Parameters:
headers: A map of header keys and values to be set on each outgoing HTTP request.
Returns:
A function that wraps an http.RoundTripper and sets the provided headers on every request before forwarding it. Existing headers with the same key will be overwritten.
func NewLoggingMiddleware ¶
func NewLoggingMiddleware(name string) func(next http.RoundTripper) http.RoundTripper
Types ¶
type CacheConfig ¶
type CacheConfig struct {
RedisClient IRedisClient
TTL time.Duration
OverrideTTL bool
Headers cacheKeyHeaders
}
CacheConfig holds the configuration for the cache middleware, including Redis client, TTL, and headers for cache key.
type CachePolicy ¶
CachePolicy defines cache control policy for a cached response, including max-age and headers used.
type HTTPClient ¶
type HTTPClient struct {
// contains filtered or unexported fields
}
func NewHTTPClient ¶
func NewHTTPClient( baseUrl string, timeout time.Duration, middlewares ...RoundTripperMiddleware) *HTTPClient
NewHTTPClient creates a new HTTPClient instance.
Params:
baseUrl: Base URL for requests (used if path is relative).
timeout: Timeout for HTTP requests.
middlewares: Optional RoundTripper middlewares.
Recommended order:
1. NewLoggingMiddleware; (Should be outermost to log all requests and responses, including cache hits and circuit breaker events)
2. NewHeaderMiddleware; (Sets custom headers before cache and circuit logic, ensuring cache keys and backend requests use the correct headers)
3. CacheMiddleware; (Checks/sets cache after headers are set, and before circuit breaker, for maximum cache efficiency)
4. CircuitBreakerMiddleware. (Protects backend only for requests that reach it, after cache and header logic)
Returns: Configured HTTP client.
func (*HTTPClient) Delete ¶
func (c *HTTPClient) Delete(ctx context.Context, path string) (*HTTPResponse, error)
Delete sends an HTTP DELETE request to the specified path.
Parameters:
- ctx: Context for cancellation and timeout.
- path: Request path or full URL.
Returns:
- *HTTPResponse: The response object.
- error: Any error encountered.
func (*HTTPClient) Get ¶
func (c *HTTPClient) Get(ctx context.Context, path string) (*HTTPResponse, error)
Get sends an HTTP GET request to the specified path.
Parameters:
- ctx: Context for cancellation and timeout.
- path: Request path or full URL.
Returns:
- *HTTPResponse: The response object.
- error: Any error encountered.
func (*HTTPClient) Head ¶
func (c *HTTPClient) Head(ctx context.Context, path string) (*HTTPResponse, error)
Head sends an HTTP HEAD request to the specified path.
Parameters:
- ctx: Context for cancellation and timeout.
- path: Request path or full URL.
Returns:
- *HTTPResponse: The response object.
- error: Any error encountered.
func (*HTTPClient) Patch ¶
func (c *HTTPClient) Patch(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)
Patch sends an HTTP PATCH request to the specified path with a request body.
Parameters:
- ctx: Context for cancellation and timeout.
- path: Request path or full URL.
- body: Request body as io.Reader.
Returns:
- *HTTPResponse: The response object.
- error: Any error encountered.
func (*HTTPClient) Post ¶
func (c *HTTPClient) Post(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)
Post sends an HTTP POST request to the specified path with a request body.
Parameters:
- ctx: Context for cancellation and timeout.
- path: Request path or full URL.
- body: Request body as io.Reader.
Returns:
- *HTTPResponse: The response object.
- error: Any error encountered.
func (*HTTPClient) Put ¶
func (c *HTTPClient) Put(ctx context.Context, path string, body io.Reader) (*HTTPResponse, error)
Put sends an HTTP PUT request to the specified path with a request body.
Parameters:
- ctx: Context for cancellation and timeout.
- path: Request path or full URL.
- body: Request body as io.Reader.
Returns:
- *HTTPResponse: The response object.
- error: Any error encountered.
type HTTPStatusError ¶
func (*HTTPStatusError) Error ¶
func (e *HTTPStatusError) Error() string
type IRedisClient ¶
type IRedisClient interface {
Get(ctx context.Context, key string) (string, error)
Set(ctx context.Context, key string, value any, expiration time.Duration) error
}
IRedisClient defines the interface for a Redis client used by the cache middleware. It must implement Get and Set methods for string keys and values.
type RoundTripperFunc ¶
RoundTripperFunc allows using ordinary functions as http.RoundTripper implementations.
type RoundTripperMiddleware ¶
type RoundTripperMiddleware func(http.RoundTripper) http.RoundTripper
RoundTripperMiddleware defines a function that wraps an http.RoundTripper with additional behavior (middleware).
type SerializableCache ¶
type SerializableCache struct {
Status string `json:"status"`
StatusCode int `json:"status_code"`
Proto string `json:"proto"`
ResponseHeaders map[string][]string `json:"header"`
Body string `json:"body"`
CacheControlValue int `json:"cacheControlValue"`
Policy CachePolicy `json:"policy"`
}
SerializableCache represents the structure of a cached HTTP response, ready for (de)serialization.