Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions cache.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cache

import (
"errors"
"fmt"
"net/http"
"time"
Expand All @@ -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 {
Expand All @@ -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)
}

Expand All @@ -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)
Expand Down