Skip to content

joeig/gin-cachecontrol

Repository files navigation

Cache-Control middleware for Gin

This Gin middleware generates cache-control headers.

Test coverage Go Report Card PkgGoDev

Setup

go get -u go.eigsys.de/gin-cachecontrol/v2
import "go.eigsys.de/gin-cachecontrol/v2"

Usage

With a preset

// Apply globally:
r.Use(cachecontrol.New(cachecontrol.NoCachePreset))

// Apply to specific routes:
cacheForever := cachecontrol.New(cachecontrol.CacheAssetsForeverPreset)
r.GET("/favicon.ico", cacheForever, faviconHandler)

Supported presets (documentation):

  • cachecontrol.NoCachePreset
  • cachecontrol.CacheAssetsForeverPreset (you may only want this for carefully selected routes)

With a custom configuration

r.Use(
    cachecontrol.New(
        cachecontrol.Config{
            MustRevalidate:       true,
            NoCache:              false,
            NoStore:              false,
            NoTransform:          false,
            Public:               true,
            Private:              false,
            ProxyRevalidate:      true,
            MaxAge:               cachecontrol.Duration(30 * time.Minute),
            SMaxAge:              nil,
            Immutable:            false,
            StaleWhileRevalidate: cachecontrol.Duration(2 * time.Hour),
            StaleIfError:         cachecontrol.Duration(2 * time.Hour),
        }
    )
)

Documentation

See Go reference.