diff --git a/cache.go b/cache.go index 828f06b..d3d7280 100644 --- a/cache.go +++ b/cache.go @@ -1,6 +1,7 @@ package cache import ( + "errors" "fmt" "net/http" "time" @@ -26,21 +27,36 @@ type Config struct { // Cache fuction called before cache a request, if false, the request is not // cached. If set Method is ignored. Cache func(r *http.Request) bool + // GetNotFoundErr is a function that returns the error that signals that the cache entry was not found. + // To maintain backwards compatibility, the default value which it returns is freecache.ErrNotFound + GetNotFoundErr func() error } -func New(cfg *Config, cache *freecache.Cache) echo.MiddlewareFunc { +func defaultGetNotFoundErr() error { + return freecache.ErrNotFound +} + +type Cache interface { + Set(key, value []byte, ttl int) error + Get(key []byte) ([]byte, error) +} + +func New(cfg *Config, cache Cache) echo.MiddlewareFunc { if cfg == nil { cfg = &Config{} } defaults.SetDefaults(cfg) + if cfg.GetNotFoundErr == nil { + cfg.GetNotFoundErr = defaultGetNotFoundErr + } m := &CacheMiddleware{cfg: cfg, cache: cache} return m.Handler } type CacheMiddleware struct { cfg *Config - cache *freecache.Cache + cache Cache } func (m *CacheMiddleware) Handler(next echo.HandlerFunc) echo.HandlerFunc { @@ -59,7 +75,7 @@ func (m *CacheMiddleware) Handler(next echo.HandlerFunc) echo.HandlerFunc { return nil } - if err != freecache.ErrNotFound { + if !errors.Is(err, m.cfg.GetNotFoundErr()) { c.Logger().Errorf("error reading cache: %s", err) } @@ -77,7 +93,7 @@ func (m *CacheMiddleware) Handler(next echo.HandlerFunc) echo.HandlerFunc { func (m *CacheMiddleware) readCache(key []byte, c echo.Context) error { if m.cfg.Refresh != nil && m.cfg.Refresh(c.Request()) { - return freecache.ErrNotFound + return m.cfg.GetNotFoundErr() } value, err := m.cache.Get(key)