github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/middlewares/cache.go (about)

     1  package middlewares
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/labstack/echo/v4"
     8  )
     9  
    10  // CacheMode is an enum to define a cache-control mode
    11  type CacheMode int
    12  
    13  const (
    14  	// NoCache is for the no-cache control mode
    15  	NoCache CacheMode = iota + 1
    16  	// NoStore is for the no-store control mode
    17  	NoStore
    18  )
    19  
    20  // CacheOptions contains different options for the CacheControl middleware.
    21  type CacheOptions struct {
    22  	MaxAge         time.Duration
    23  	Private        bool
    24  	MustRevalidate bool
    25  	Mode           CacheMode
    26  }
    27  
    28  // CacheControl returns a middleware to handle HTTP caching options.
    29  func CacheControl(opts CacheOptions) echo.MiddlewareFunc {
    30  	return func(next echo.HandlerFunc) echo.HandlerFunc {
    31  		return func(c echo.Context) error {
    32  			cache := "public"
    33  			if opts.Private {
    34  				cache = "private"
    35  			}
    36  			switch opts.Mode {
    37  			case NoCache:
    38  				cache = appendHeader(cache, "no-cache")
    39  			case NoStore:
    40  				cache = appendHeader(cache, "no-store")
    41  			}
    42  			if opts.MustRevalidate {
    43  				cache = appendHeader(cache, "must-revalidate")
    44  			}
    45  			if maxAge := opts.MaxAge; maxAge > 0 {
    46  				cache = appendHeader(cache, fmt.Sprintf("max-age=%d", int(maxAge.Seconds())))
    47  			}
    48  			if cache != "" {
    49  				c.Response().Header().Set("Cache-Control", cache)
    50  			}
    51  			return next(c)
    52  		}
    53  	}
    54  }
    55  
    56  func appendHeader(h, val string) string {
    57  	if h == "" {
    58  		return val
    59  	}
    60  	return h + ", " + val
    61  }