Skip to content

Commit

Permalink
Fix: add cache skipper
Browse files Browse the repository at this point in the history
  • Loading branch information
aopoltorzhicky committed Nov 15, 2023
1 parent eb8d152 commit 70abf1e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
19 changes: 10 additions & 9 deletions cmd/api/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"sync"

"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/pkg/errors"
)

Expand Down Expand Up @@ -60,24 +61,24 @@ func (c *Cache) Clear() {
}

type CacheMiddleware struct {
cache *Cache
cache *Cache
skipper middleware.Skipper
}

func Middleware(cache *Cache) echo.MiddlewareFunc {
func Middleware(cache *Cache, skipper middleware.Skipper) echo.MiddlewareFunc {
mdlwr := CacheMiddleware{
cache: cache,
cache: cache,
skipper: skipper,
}
return mdlwr.Handler
}

func (m *CacheMiddleware) isCacheable(req *http.Request) bool {
return req.Method == http.MethodGet
}

func (m *CacheMiddleware) Handler(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !m.isCacheable(c.Request()) {
return next(c)
if m.skipper != nil {
if m.skipper(c) {
return next(c)
}
}
path := c.Request().URL.String()

Expand Down
14 changes: 12 additions & 2 deletions cmd/api/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,17 @@ func gzipSkipper(c echo.Context) bool {
if strings.Contains(c.Request().URL.Path, "metrics") {
return true
}
if strings.Contains(c.Request().URL.Path, "ws") {
return websocketSkipper(c)
}

func cacheSkipper(c echo.Context) bool {
if c.Request().Method != http.MethodGet {
return true
}
if websocketSkipper(c) {
return true
}
if strings.Contains(c.Request().URL.Path, "metrics") {
return true
}
return false
Expand Down Expand Up @@ -173,7 +183,7 @@ func initEcho(cfg ApiConfig, env string) *echo.Echo {
endpointCache = cache.NewCache(cache.Config{
MaxEntitiesCount: 1000,
})
e.Use(cache.Middleware(endpointCache))
e.Use(cache.Middleware(endpointCache, cacheSkipper))
}

timeout := 30 * time.Second
Expand Down

0 comments on commit 70abf1e

Please sign in to comment.