From d17feacc34304cdc5db8939d1d98c38936dd0f1d Mon Sep 17 00:00:00 2001 From: Trong Huu Nguyen Date: Tue, 14 Feb 2023 14:20:35 +0100 Subject: [PATCH] refactor(handler/autologin): use sync.Map for cache --- pkg/handler/autologin/autologin.go | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/pkg/handler/autologin/autologin.go b/pkg/handler/autologin/autologin.go index f3461f5..734d421 100644 --- a/pkg/handler/autologin/autologin.go +++ b/pkg/handler/autologin/autologin.go @@ -18,8 +18,7 @@ var DefaultIgnorePatterns = []string{ type AutoLogin struct { Enabled bool IgnorePatterns []string - cache map[string]bool - lock sync.Mutex + cache sync.Map } func (a *AutoLogin) NeedsLogin(r *http.Request, isAuthenticated bool) bool { @@ -27,9 +26,6 @@ func (a *AutoLogin) NeedsLogin(r *http.Request, isAuthenticated bool) bool { return false } - a.lock.Lock() - defer a.lock.Unlock() - path := r.URL.Path if !strings.HasPrefix(path, "/") { path = "/" + path @@ -39,19 +35,19 @@ func (a *AutoLogin) NeedsLogin(r *http.Request, isAuthenticated bool) bool { path = strings.TrimSuffix(path, "/") } - if result, found := a.cache[path]; found { - return result + if result, found := a.cache.Load(path); found { + return result.(bool) } for _, pattern := range a.IgnorePatterns { match, _ := doublestar.Match(pattern, path) if match { - a.cache[path] = false + a.cache.Store(path, false) return false } } - a.cache[path] = true + a.cache.Store(path, true) return true } @@ -77,6 +73,6 @@ func New(cfg *config.Config) (*AutoLogin, error) { return &AutoLogin{ Enabled: cfg.AutoLogin, IgnorePatterns: patterns, - cache: make(map[string]bool), + cache: sync.Map{}, }, nil }