httpcache

package
v14.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 16 Imported by: 0

README

HTTP Cache Middleware for Iris

A high-performance HTTP response caching middleware for Iris using DragonflyDB/Redis as a backend. It supports flexible cache key generation based on request path, method, query parameters, body, headers, and cookies, and provides efficient cache invalidation for dynamic APIs.

Features

  • Plug-and-play Iris middleware for GET and POST endpoints.
  • DragonflyDB/Redis backend for fast, scalable caching.
  • Customizable cache key generation: include/exclude query, body, headers, cookies.
  • Efficient cache invalidation: by request, by prefix, or by path.
  • Batched SCAN+DEL for safe production cache cleanup.
  • Only caches successful (HTTP 200) responses by default.

Installation

To use the httpcache middleware, you need to import it in your Iris application:

import "github.com/kataras/iris/v14/middleware/cache/httpcache"

Usage

1. Configure and Initialize the Cache
import "github.com/kataras/iris/v14/middleware/cache/httpcache"

cache, err := httpcache.New(httpcache.Options{
    Addr:     "localhost:6379",
    Password: "",
    TTL:      10 * time.Minute,
    Headers:  []string{"Authorization"}, // Optional: include headers in cache key
    Cookies:  []string{"session_id"},    // Optional: include cookies in cache key
    StartupCleanup: true, // Optional: clean up cache on startup.
})
if err != nil {
    log.Fatalf("failed to initialize cache: %v", err)
}
// Or, to panic instead of reporting the error:
//	cache := httpcache.Must(httpcache.Options{...})
defer cache.Close()
2. Register the Middleware in Iris
app := iris.New()
app.Use(cache.Handler())
3. Invalidate Cache When Data Changes
Invalidate all cached user lists after a user is deleted:
// In your controller after deleting a user:
prefix := "httpcache:/users/list:POST:"
deleted, err := cache.InvalidatePrefix(ctx, prefix)

Cache Key Structure

The cache key is generated as:

httpcache:<route_tmpl>:<method>:<url_path>[:<query_hash>][:<body_hash>][:<headers_hash>][:<cookies_hash>]
  • route_tmpl: The route template (e.g. /users/{id:uuid})
  • method: HTTP method (GET, POST, etc.)
  • url_path: The request path (e.g. /users/2707df68-5f7b-480a-a8b8-365830b39a20)
  • query_hash: SHA256 of the query string (optional)
  • body_hash: SHA256 of the request body (optional)
  • headers_hash: SHA256 of selected headers (optional)
  • cookies_hash: SHA256 of selected cookies (optional)

You can control which parts are included via the Options struct.

Example

package main

import (
    "log"
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/cache/httpcache"
)

func main() {
    cache, err := httpcache.New(httpcache.Options{
        Addr:     "localhost:6379",
        TTL:      5 * time.Minute,
        Headers:  []string{"Authorization"},
    })
    if err != nil {
        log.Fatal(err)
    }
    defer cache.Close()

    app := iris.New()
    app.Use(cache.Handler())

    app.Get("/hello", func(ctx iris.Context) {
        ctx.WriteString("Hello, world!")
    })

    app.Listen(":8080")
}

Controller Example with Invalidation

type UserController struct {
	cache *httpcache.Cache
}

func NewUserController(cache *httpcache.Cache) *UserController {
	return &UserController{
		cache:        cache,
	}
}

func (c *UserController) Routing(r router.Router) {
	// caching := c.cache.Handler()
	// invalidating := c.cache.InvalidateHandler()
    // OR:
    // invalidating := c.cache.InvalidateRoutes(r)
    // OR:
    caching, invalidating := c.cache.Pair(r)

	r.Post("/signup", invalidating, c.signup)
	r.Post("/signin", caching, c.signin)
	r.Delete("/", invalidating, c.deleteUser)
	r.Post("/restore", invalidating, c.restoreDeletedUser)
	r.Post("/request-password-reset", c.requestPasswordReset)
	r.Post("/reset-password", invalidating, c.resetPassword)
	r.Put("/", invalidating, c.updateUsers)
	r.Post("/list", caching, c.listUsers)
}

// [...implement the controller methods like signup, signin, deleteUser, etc.]
app := iris.New()
// [...]

cache, err := httpcache.New(httpcache.Options{
        Addr:     "localhost:6379",
        Password: "kataras!123", // Optional: set password if your Redis requires it.
        TTL:      5 * time.Minute,
        Headers:  []string{"Authorization"},
})
if err != nil {
    panic(fmt.Errorf("failed to connect to the cache: %w", err))
}

app.Router("/u", cache, NewUserController)

Best Practices

  • Invalidate cache after any data-changing operation (create, update, delete).
  • Use prefix invalidation for endpoints with many possible query/body variations.
  • Include headers/cookies in the cache key if responses are user/session-specific.
  • Monitor cache hit/miss rates for tuning.

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func PathPrefix

func PathPrefix(r *http.Request) string

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 Must

func Must(options Options) *Cache

Must is New but it panics instead of reporting the error.

func New

func New(options Options) (*Cache, error)

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) Close

func (c *Cache) Close() error

Close closes the underlying DragonflyDB/Redis connection.

func (*Cache) ContextKey

func (c *Cache) ContextKey(ctx *context.Context) string

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) CountAll

func (c *Cache) CountAll(ctx context.Context) (int, error)

CountAll returns the total number of cache entries.

func (*Cache) CountPrefix

func (c *Cache) CountPrefix(ctx context.Context, prefix string) (int, error)

CountPrefix returns the number of cache keys that match the given prefix.

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key string) (Response, bool, error)

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

func (c *Cache) GetResponse(ctx context.Context, r *http.Request) (Response, bool, error)

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

func (c *Cache) Handler() context.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

func (c *Cache) Invalidate(ctx context.Context, key string) error

Invalidate deletes a specific cache entry by its key. Returns an error if the deletion fails.

func (*Cache) InvalidateAll

func (c *Cache) InvalidateAll(ctx context.Context) (int, error)

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

func (c *Cache) InvalidateHandler(prefixes ...string) context.Handler

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

func (c *Cache) InvalidatePrefix(ctx context.Context, prefix string) (int, error)

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

func (c *Cache) InvalidateRequest(ctx context.Context, r *http.Request) error

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

func (c *Cache) InvalidateRoutes(r router.Router) context.Handler

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

func (c *Cache) RequestKey(r *http.Request) string

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

func (c *Cache) Set(ctx context.Context, key string, response Response) error

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

func (c *Cache) SetResponse(ctx context.Context, r *http.Request, response Response) error

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.

func (*Response) WriteTo

func (r *Response) WriteTo(w http.ResponseWriter) error

WriteTo writes the cached response to the provided http.ResponseWriter.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL