Documentation
¶
Overview ¶
Package idempotency provides HTTP middleware for idempotent request handling. It prevents duplicate processing of requests by caching responses based on idempotency keys, commonly used in payment and financial APIs.
Index ¶
Constants ¶
const ( // DefaultHeaderName is the default HTTP header for idempotency keys DefaultHeaderName = "Idempotency-Key" // DefaultTTL is the default time-to-live for cached responses DefaultTTL = 24 * time.Hour )
Variables ¶
var ( // ErrRequestInProgress is returned when a request with the same key is already being processed ErrRequestInProgress = errors.New("request with this idempotency key is already in progress") // ErrNotFound is returned when a cached response is not found ErrNotFound = errors.New("cached response not found") // ErrLockFailed is returned when acquiring a lock fails ErrLockFailed = errors.New("failed to acquire lock") )
Functions ¶
func Middleware ¶
Middleware returns an HTTP middleware that enforces idempotency. It checks for an idempotency key in the request header, and if found, either returns a cached response or processes and caches the new response.
Types ¶
type CachedResponse ¶
type CachedResponse struct {
StatusCode int `json:"status_code"`
Headers http.Header `json:"headers"`
Body []byte `json:"body"`
Timestamp time.Time `json:"timestamp"`
}
CachedResponse represents a cached HTTP response
type Option ¶
type Option func(*Config)
Option is a functional option for configuring the middleware
func WithHeaderName ¶
WithHeaderName sets the HTTP header name for idempotency keys
func WithKeyFunc ¶
WithKeyFunc sets a custom key generation function
type Store ¶
type Store interface {
// Get retrieves a cached response by key
Get(key string) (*CachedResponse, error)
// Set stores a response with the given key and TTL
Set(key string, response *CachedResponse, ttl time.Duration) error
// Lock acquires a lock for the given key to prevent concurrent processing
// Returns an unlock function that must be called to release the lock
Lock(key string) (unlock func(), err error)
}
Store defines the interface for storing and retrieving cached responses