cache

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: 7 Imported by: 0

README

Cache Middleware for Iris

This middleware sets the HTTP caching headers on your responses: ETag, Cache-Control, Last-Modified, Expires, Pragma, Vary and Proxy-Authenticate. It also answers a conditional request whose If-None-Match still matches with 304, so the body never goes out twice.

For a server-side response store rather than cache headers, see httpcache.

Features of Cache Middleware

The cache middleware offers a variety of features to control HTTP caching behavior. These features include:

  1. ETag Headers: Used for cache validation.
  2. Cache-Control Headers: Directives to control caching behavior.
  3. Last-Modified Headers: Used for cache validation.
  4. Expires Headers: Specifies the expiration time of the cached resource.
  5. Pragma Headers: HTTP/1.0 header for backward compatibility.
  6. Vary Headers: Specifies how caches should treat the response based on request headers.
  7. Proxy-Authenticate Headers: Specifies the authentication method for accessing a resource behind a proxy server.

Installation

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

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

Usage

Basic Setup

To use the cache middleware, you need to import the necessary packages and configure the middleware with your desired options. Here is a basic example:

package main

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/middleware/cache"
)

func main() {
	app := iris.New()
	app.Use(cache.New(cache.DefaultOptions))

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

	app.Listen(":8080")
}
Configuration Options

The Options struct controls which headers the middleware sets:

  • ETag: Whether to use ETag headers for cache validation.
  • CacheControl: The Cache-Control directives to include in the response headers.
  • LastModified: Whether to use Last-Modified headers for cache validation.
  • Expires: Duration for the Expires header.
  • Pragma: The Pragma directive to include in the response headers.
  • Vary: The Vary header specifies how caches should treat the response based on request headers.
  • ProxyAuthenticate: The Proxy-Authenticate header specifies the authentication method for accessing a resource behind a proxy server.
Example Configuration

Here is an example of how to configure the cache middleware with custom options:

package main

import (
	"time"

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

func main() {
	app := iris.New()
	options := cache.Options{
		ETag:         true,
		CacheControl: cache.NewCacheControlBuilder().Public().MaxAge(time.Hour).SMaxAge(2 * time.Hour).MustRevalidate().ProxyRevalidate().Build(),
		LastModified: true,
		Expires:      24 * time.Hour,
		Pragma:       cache.NoPragmaCache,
		Vary:         cache.NewVaryBuilder().AcceptEncoding().Build(),
		ProxyAuthenticate: cache.NewProxyAuthenticateBuilder().Basic("Restricted Area").Build(),
	}
	app.Use(cache.New(options))

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

	app.Listen(":8080")
}
Cache-Control Directives

The CacheControlBuilder helps you build the Cache-Control header value. Here are some of the available methods:

  • Public: Indicates that the response may be cached by any cache.
  • Private: Indicates that the response is intended for a single user and must not be cached by shared caches.
  • NoCache: Indicates that the response must not be used from the cache without revalidation with the origin server.
  • NoStore: Indicates that the response must not be stored in any cache.
  • MaxAge: Specifies the maximum amount of time a resource is considered fresh. Takes a time.Duration, written in whole seconds; a value above zero and below one second panics (MaxAge(3600) is 3600 nanoseconds, write MaxAge(time.Hour)).
  • SMaxAge: Specifies the maximum amount of time a resource is considered fresh in shared caches. Takes a time.Duration, same rules as MaxAge.
  • MustRevalidate: Indicates that once a resource becomes stale, it must be validated with the origin server before being used.
  • ProxyRevalidate: Indicates that shared caches (e.g., proxies) must revalidate the response with the origin server once it becomes stale.
Vary Header

The VaryBuilder helps you build the Vary header value. Here are some of the available methods:

  • Accept: Sets the Vary directive to 'Accept'.
  • AcceptEncoding: Sets the Vary directive to 'Accept-Encoding'.
  • AcceptLanguage: Sets the Vary directive to 'Accept-Language'.
  • UserAgent: Sets the Vary directive to 'User-Agent'.
Proxy-Authenticate Header

The ProxyAuthenticateBuilder helps you build the Proxy-Authenticate header value. Here are some of the available methods:

  • Basic: Sets the Proxy-Authenticate scheme to 'Basic'.
  • Digest: Sets the Proxy-Authenticate scheme to 'Digest'.

Testing

To check that your caching middleware behaves as expected, write tests with the httptest package that ships with Iris. Here is an example test:

package cache_test

import (
	"net/http"
	"testing"
	"time"

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

func TestCache(t *testing.T) {
	app := iris.New()
	options := cache.DefaultOptions
	app.Use(cache.New(options))

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

	resp := httptest.New(t, app).GET("/foo").Expect().Status(http.StatusOK)

	if got, want := resp.Header("Cache-Control").Raw(), options.CacheControl; got != want {
		t.Errorf("Cache-Control header = %q, want %q", got, want)
	}

	if got, want := resp.Header("Pragma").Raw(), options.Pragma; got != want {
		t.Errorf("Pragma header = %q, want %q", got, want)
	}

	if got, want := resp.Header("Vary").Raw(), options.Vary; got != want {
		t.Errorf("Vary header = %q, want %q", got, want)
	}

	if got := resp.Header("ETag").Raw(); got == "" {
		t.Errorf("Expected ETag header to be set")
	}

	expires := time.Now().Add(options.Expires).Format(http.TimeFormat)
	if got, want := resp.Header("Expires").Raw(), expires; got != want {
		t.Errorf("Expires header = %q, want %q", got, want)
	}

	if got, want := resp.Header("Proxy-Authenticate").Raw(), options.ProxyAuthenticate; got != want {
		t.Errorf("Proxy-Authenticate header = %q, want %q", got, want)
	}
}

Documentation

Overview

Package cache sets client- and proxy-cache headers (Cache-Control, ETag, Last-Modified, Expires, Pragma, Vary, Proxy-Authenticate) on the response.

Its entry point is New(Options), which returns a Handler and cannot fail. `Strict` is New with one extra rule for credentialed requests; read the SECURITY WARNING on DefaultOptions before registering either one globally. For a server-side response store see the sibling cache/httpcache package.

Index

Constants

View Source
const (
	// NoPragmaCache is an HTTP/1.0 header used for backwards compatibility, instructing caches not to store the response.
	NoPragmaCache string = "no-cache"
)

Variables

View Source
var DefaultOptions = Options{
	ETag:         true,
	CacheControl: NewCacheControlBuilder().Public().MaxAge(time.Hour).SMaxAge(2 * time.Hour).MustRevalidate().ProxyRevalidate().Build(),
	LastModified: true,
	Expires:      24 * time.Hour,
	Pragma:       NoPragmaCache,
	Vary:         NewVaryBuilder().AcceptEncoding().Build(),
}

DefaultOptions are the default options for the caching middleware. These options are used when the middleware is created without any options. The default options are: - ETag: true - CacheControl: public, max-age=3600, s-maxage=7200, must-revalidate, proxy-revalidate - LastModified: true - Expires: 24 hours - Pragma: no-cache - Vary: Accept-Encoding To create a new middleware with the default options, use:

app.Use(cache.New(cache.DefaultOptions))

SECURITY WARNING: these defaults declare every response "public" and list only Accept-Encoding in Vary.

"public" is not decoration. Per RFC 9111 it is the directive that authorizes a shared cache - a CDN, a corporate proxy, nginx proxy_cache - to store a response even though the request carried credentials. Applied broadly, which is what app.Use does, that means an authenticated /account response can be stored under a URL-only key for an hour and served to the next visitor.

Register this per route, on the routes you know are the same for everybody. For a route that serves both anonymous and authenticated callers, use `Strict`, which keeps this policy for the former and downgrades it for the latter. For a route that is always user-specific, use `PrivateOptions`.

View Source
var PrivateOptions = Options{
	ETag:         true,
	CacheControl: NewCacheControlBuilder().Private().MaxAge(0).MustRevalidate().Build(),
	LastModified: true,
	Pragma:       NoPragmaCache,
	Vary:         NewVaryBuilder().AcceptEncoding().Build(),
}

PrivateOptions are DefaultOptions with a private, shorter-lived policy: a response may be stored by the client's own browser but never by a shared cache.

Prefer these whenever responses can be user-specific.

Functions

func New

func New(options Options) context.Handler

New returns a new Iris middleware that sets caching headers based on the provided options.

The headers are set for every request that reaches it, so register it on the routes whose responses are the same for every client. See the SECURITY WARNING on DefaultOptions.

Example:

app.Use(cache.New(cache.Options{
	ETag:         true,
	CacheControl: cache.NewCacheControlBuilder().Public().MaxAge(time.Hour).SMaxAge(2 * time.Hour).MustRevalidate().ProxyRevalidate().Build(),
	LastModified: true,
	Expires:      24 * time.Hour,
	Pragma:       "no-cache",
	Vary:         cache.NewVaryBuilder().AcceptEncoding().Build(),
}))

func Strict

func Strict(options Options) context.Handler

Strict is New with one extra rule: a request that carries credentials (`Authorization`, `Proxy-Authorization` or `Cookie`) never receives a shared-cache directive.

`New` applies your options to every request, which is correct when the response is the same for everybody. It is the wrong answer when it is not: `public` and `s-maxage` are precisely what authorize a CDN or a corporate proxy to store a response that was fetched with credentials and hand it to the next visitor.

Strict lets you keep an aggressive shared-cache policy for anonymous traffic and fall back to a private one the moment a request identifies its client:

app.Use(cache.Strict(cache.DefaultOptions))

Validators (`ETag`, `Last-Modified`) and `Vary` are applied either way; only the Cache-Control and Expires policy is downgraded. Use it when one route serves both anonymous and authenticated callers. When a route is public for everyone, `New` is the better fit and keeps the shared cache working.

Types

type CacheControlBuilder

type CacheControlBuilder struct {
	// contains filtered or unexported fields
}

CacheControlBuilder helps to build the Cache-Control header value.

func NewCacheControlBuilder

func NewCacheControlBuilder() *CacheControlBuilder

NewCacheControlBuilder creates a new CacheControlBuilder.

func (*CacheControlBuilder) Build

func (b *CacheControlBuilder) Build() string

Build constructs the Cache-Control header value from the added directives.

func (*CacheControlBuilder) MaxAge

MaxAge sets the Cache-Control directive to 'max-age=<seconds>'. MaxAge specifies the maximum amount of time a resource is considered fresh. The duration is written in whole seconds (a fraction of a second is dropped), for example MaxAge(time.Hour) writes "max-age=3600". Zero writes "max-age=0".

It panics if d is negative, or above zero but below one second: a bare number such as MaxAge(3600) is 3600 nanoseconds, not an hour.

func (*CacheControlBuilder) MustRevalidate

func (b *CacheControlBuilder) MustRevalidate() *CacheControlBuilder

MustRevalidate sets the Cache-Control directive to 'must-revalidate'. MustRevalidate indicates that once a resource becomes stale, it must be validated with the origin server before being used.

func (*CacheControlBuilder) NoCache

NoCache sets the Cache-Control directive to 'no-cache'. NoCache indicates that the response must not be used from the cache without revalidation with the origin server.

func (*CacheControlBuilder) NoStore

NoStore sets the Cache-Control directive to 'no-store'. NoStore indicates that the response must not be stored in any cache.

func (*CacheControlBuilder) Private

Private sets the Cache-Control directive to 'private'. Private indicates that the response is intended for a single user and must not be cached by shared caches.

func (*CacheControlBuilder) ProxyRevalidate

func (b *CacheControlBuilder) ProxyRevalidate() *CacheControlBuilder

ProxyRevalidate sets the Cache-Control directive to 'proxy-revalidate'. ProxyRevalidate indicates that shared caches (e.g., proxies) must revalidate the response with the origin server once it becomes stale.

func (*CacheControlBuilder) Public

Public sets the Cache-Control directive to 'public'. Public indicates that the response may be cached by any cache.

func (*CacheControlBuilder) SMaxAge

SMaxAge sets the Cache-Control directive to 's-maxage=<seconds>'. SMaxAge specifies the maximum amount of time a resource is considered fresh in shared caches. The duration is written in whole seconds, the same way as MaxAge, and SMaxAge panics on the same values.

type Options

type Options struct {
	// Whether to use ETag headers for cache validation.
	ETag bool
	// The Cache-Control directives to include in the response headers.
	// Use the CacheControlBuilder to construct this value.
	CacheControl string
	// Whether to use Last-Modified headers for cache validation.
	LastModified bool
	// Duration for the Expires header.
	Expires time.Duration
	// The Pragma directive to include in the response headers,
	// e.g.  NoPragmaCache.
	Pragma string
	// The Vary header specifies how caches should treat the response based on request headers.
	// Use the VaryBuilder to construct this value.
	Vary string
	// The Proxy-Authenticate header is used to specify the authentication method
	// that should be used to access a resource behind a proxy server.
	// Use the ProxyAuthenticateBuilder to construct this value, e.g.
	// NewProxyAuthenticateBuilder().Basic("Restricted Area").Build()
	ProxyAuthenticate string
}

Options holds configuration options for the caching middleware.

type ProxyAuthenticateBuilder

type ProxyAuthenticateBuilder struct {
	// contains filtered or unexported fields
}

ProxyAuthenticateBuilder helps to build the Proxy-Authenticate header value.

func NewProxyAuthenticateBuilder

func NewProxyAuthenticateBuilder() *ProxyAuthenticateBuilder

NewProxyAuthenticateBuilder creates a new ProxyAuthenticateBuilder.

func (*ProxyAuthenticateBuilder) Basic

Basic sets the Proxy-Authenticate scheme to 'Basic'.

func (*ProxyAuthenticateBuilder) Build

func (b *ProxyAuthenticateBuilder) Build() string

Build constructs the Proxy-Authenticate header value from the added schemes.

func (*ProxyAuthenticateBuilder) Digest

func (b *ProxyAuthenticateBuilder) Digest(realm, nonce, opaque string) *ProxyAuthenticateBuilder

Digest sets the Proxy-Authenticate scheme to 'Digest'.

type VaryBuilder

type VaryBuilder struct {
	// contains filtered or unexported fields
}

VaryBuilder helps to build the Vary header value.

func NewVaryBuilder

func NewVaryBuilder() *VaryBuilder

NewVaryBuilder creates a new VaryBuilder.

func (*VaryBuilder) Accept

func (b *VaryBuilder) Accept() *VaryBuilder

Accept sets the Vary directive to 'Accept'.

func (*VaryBuilder) AcceptEncoding

func (b *VaryBuilder) AcceptEncoding() *VaryBuilder

AcceptEncoding sets the Vary directive to 'Accept-Encoding'.

func (*VaryBuilder) AcceptLanguage

func (b *VaryBuilder) AcceptLanguage() *VaryBuilder

AcceptLanguage sets the Vary directive to 'Accept-Language'.

func (*VaryBuilder) Add

func (b *VaryBuilder) Add(directive string) *VaryBuilder

Add appends a directive to the Vary header value.

func (*VaryBuilder) Build

func (b *VaryBuilder) Build() string

Build constructs the Vary header value from the added directives.

func (*VaryBuilder) UserAgent

func (b *VaryBuilder) UserAgent() *VaryBuilder

UserAgent sets the Vary directive to 'User-Agent'.

Directories

Path Synopsis
Package httpcache provides a middleware for caching HTTP responses in DragonflyDB or Redis.
Package httpcache provides a middleware for caching HTTP responses in DragonflyDB or Redis.

Jump to

Keyboard shortcuts

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