Documentation
¶
Overview ¶
Package httpcache provides a middleware for caching HTTP responses in DragonflyDB or Redis. It allows caching of GET and POST requests to improve performance by reducing the need for repeated processing of the same requests.
Its entry point is New(Options) (*Cache, error), which reports a failed connection to the store; `Must` is the panicking companion. It returns a *Cache rather than a Handler because the store is also used directly, to invalidate entries; register its `Handler` method.
Index ¶
- func PathPrefix(r *http.Request) string
- type Cache
- func (c *Cache) Close() error
- func (c *Cache) ContextKey(ctx *context.Context) string
- func (c *Cache) CountAll(ctx context.Context) (int, error)
- func (c *Cache) CountPrefix(ctx context.Context, prefix string) (int, error)
- func (c *Cache) Get(ctx context.Context, key string) (Response, bool, error)
- func (c *Cache) GetResponse(ctx context.Context, r *http.Request) (Response, bool, error)
- func (c *Cache) Handler() context.Handler
- func (c *Cache) Invalidate(ctx context.Context, key string) error
- func (c *Cache) InvalidateAll(ctx context.Context) (int, error)
- func (c *Cache) InvalidateHandler(prefixes ...string) context.Handler
- func (c *Cache) InvalidatePrefix(ctx context.Context, prefix string) (int, error)
- func (c *Cache) InvalidateRequest(ctx context.Context, r *http.Request) error
- func (c *Cache) InvalidateRoutes(r router.Router) context.Handler
- func (c *Cache) Pair(r router.Router) (context.Handler, context.Handler)
- func (c *Cache) RequestKey(r *http.Request) string
- func (c *Cache) Set(ctx context.Context, key string, response Response) error
- func (c *Cache) SetResponse(ctx context.Context, r *http.Request, response Response) error
- type Options
- type Response
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func PathPrefix ¶
PathPrefix generates a cache key prefix based on the request URL path.
Types ¶
type Cache ¶
type Cache struct {
Options *Options
// contains filtered or unexported fields
}
Cache represents a DragonflyDB/Redis cache for HTTP responses. It provides methods to set and get cached responses, generate cache keys, and invalidate cache entries based on request URLs or prefixes.
func New ¶
New creates and returns a new Cache instance using the provided options. Returns an error if the connection to DragonflyDB/Redis fails. See the `Must` companion.
func (*Cache) ContextKey ¶
ContextKey generates a unique cache key for the current context. The key format is: httpcache:<route_tmpl>:<method>:<url_path>[:<query_hash>][:<body_hash>][:<headers_hash>][:<cookies_hash>] If the route is static, it uses the path and method. If the route is dynamic, it uses the route's template source, path, and method. The key is then appended with a suffix that includes the request's query, body, headers, and cookies hashes. This ensures that the cache key is unique for each request, even if the path and method are the same. This key is used to store and retrieve cached responses for the current request. If the cache is disabled, it returns an empty string. Examples: - httpcache:/users/list:POST - httpcache:/u/{identifier:string}:GET
func (*Cache) CountPrefix ¶
CountPrefix returns the number of cache keys that match the given prefix.
func (*Cache) Get ¶
Get retrieves the cached response for a given key. Returns the cached response, a boolean indicating if it was found, and any error encountered.
func (*Cache) GetResponse ¶
GetResponse retrieves the cached response for a specific HTTP request. It uses a cache key derived from the request's URL path, method, query parameters, and body. Returns the cached response, a boolean indicating if it was found, and any error encountered.
func (*Cache) Handler ¶
Handler is an Iris middleware handler that caches HTTP responses. It uses the provided Cache instance to store and retrieve cached responses. The handler checks the request method and only caches responses for GET and POST requests. If a cached response is found, it writes it directly to the context response. If no cached response is found, it records the response using a response recorder. After the handler chain is executed, if the response status code is 200, it stores the response body in the cache using a key derived from the request. The cache key is generated based on the request's URL path, method, query parameters, headers, cookies and body.
The cache is designed to store only successful responses (HTTP 200) for GET and POST requests.
func (*Cache) Invalidate ¶
Invalidate deletes a specific cache entry by its key. Returns an error if the deletion fails.
func (*Cache) InvalidateAll ¶
InvalidateAll deletes all cache entries by using a wildcard prefix. This is useful for clearing the entire cache. Returns the number of deleted keys and any error encountered. Note: This operation can be expensive if the cache contains a large number of entries. It is recommended to use this with caution in production environments.
func (*Cache) InvalidateHandler ¶
InvalidateHandler returns an Iris middleware handler that invalidates the cache after a resource mutation operation (DELETE, POST, PUT, PATCH). It checks the request method and status code to determine if cache invalidation is necessary. If the status code is 200, 201, or 204 and the method is one of DELETE, POST, PUT, or PATCH, it invalidates the cache entries for the specified prefixes. If no prefixes are provided, it invalidates all cache entries. If an error occurs during invalidation, it sets the error in the context.
func (*Cache) InvalidatePrefix ¶
InvalidatePrefix deletes all cache entries with the given prefix as fast as possible. For Redis >= 6.0, UNLINK is used for asynchronous deletion (faster than DEL). Falls back to DEL if UNLINK is not available. Returns the number of deleted keys and any error encountered.
func (*Cache) InvalidateRequest ¶
InvalidateRequest deletes the cache entry for a specific HTTP request. It uses a cache key derived from the request's URL path, method, query parameters, and body. Returns an error if the deletion fails.
func (*Cache) InvalidateRoutes ¶
InvalidateRoutes returns an Iris middleware handler that invalidates the cache for all routes of the provided router after a resource mutation operation (DELETE, POST, PUT, PATCH). It collects all route prefixes that have the cache handler registered and invalidates them.
func (*Cache) Pair ¶
Pair returns two Iris middleware handlers: 1. A cache handler that caches HTTP responses for GET, QUERY and POST requests. 2. An invalidate handler that invalidates the cache for the specific routes that the cache handler was registered on. Read more about the cache handler in the `Handler` method. Read more about the invalidate handler in the `InvalidateRoutes` method.
func (*Cache) RequestKey ¶
RequestKey generates a unique cache key for the given HTTP request. The key is derived from the request's URL path, method, query parameters, and body. The key format is: httpcache:<url_path_only>:<method>:<query_hash>:<body_hash>[:<headers_hash>][:<cookies_hash>]
func (*Cache) Set ¶
Set stores the response in the cache under the given key, as it is. Use RequestKey to build a key out of a request, or SetResponse to let it derive one. Key format (as produced by RequestKey): httpcache:<url_path_only>:<method>:<query_hash>:<body_hash> Example: httpcache:/users/list:POST:abcdef:123456
func (*Cache) SetResponse ¶
SetResponse stores the response for a specific HTTP request in the cache. We cache the response body and its headers, not the status code. The built-in handler strips the per-client headers (Set-Cookie, hop-by-hop and so on) before it reaches this method, see cacheableHeaders. As the cache is designed for GET & POST, 200s requests.
type Options ¶
type Options struct {
// If true, the cache is disabled, even if the fields are filled, and no operations will be performed.
Disable bool `json:"disable" yaml:"Disable"`
// If true, it will delete all keys in the cache on startup.
StartupCleanup bool `json:"startup_cleanup" yaml:"StartupCleanup"`
// DragonflyDB/Redis address.
Addr string `json:"addr" yaml:"Addr"`
// DragonflyDB/Redis optional password.
Password string `json:"-" yaml:"Password"`
// Time to live for cache entries. Defaults to 10 minutes.
TTL time.Duration `json:"ttl" yaml:"TTL"`
// Timeout for cache commands. Defaults to 15 seconds.
CommandTimeout time.Duration `json:"command_timeout" yaml:"CommandTimeout"`
// If true, do not include request body in cache key generation.
NoBody bool `json:"no_body" yaml:"NoBody"`
// If true, do not include query parameters in cache key generation.
NoQuery bool `json:"no_query" yaml:"NoQuery"`
// Headers to include in cache key generation. E.g. Authorization.
Headers []string `json:"headers" yaml:"Headers"`
// Cookies to include in cache key generation. E.g. session_id.
Cookies []string `json:"cookies" yaml:"Cookies"`
}
Options defines the configuration options for the DragonflyDB/Redis cache. It includes the address, password, TTL for cache entries, command timeout, and options for excluding request body and query parameters from cache key generation.
type Response ¶
type Response struct {
ExpiresAt time.Time `json:"expired_at"` // Expiration time for the cached response.
Body []byte `json:"body"`
Headers http.Header `json:"headers"` // Including content-type and other headers.
}
Response represents a cached HTTP response. It includes the response body, headers, and expiration time.