From 07fc0e24dd8bb4e4fd1697c8480a2531c0296b57 Mon Sep 17 00:00:00 2001 From: Trong Huu Nguyen Date: Wed, 4 Jan 2023 15:46:08 +0100 Subject: [PATCH] perf(handler/autologin): cache NeedsLogin results --- pkg/handler/autologin/autologin.go | 31 +++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/pkg/handler/autologin/autologin.go b/pkg/handler/autologin/autologin.go index 8e10b49..f3461f5 100644 --- a/pkg/handler/autologin/autologin.go +++ b/pkg/handler/autologin/autologin.go @@ -3,6 +3,7 @@ package autologin import ( "net/http" "strings" + "sync" "github.com/bmatcuk/doublestar/v4" @@ -17,6 +18,8 @@ var DefaultIgnorePatterns = []string{ type AutoLogin struct { Enabled bool IgnorePatterns []string + cache map[string]bool + lock sync.Mutex } func (a *AutoLogin) NeedsLogin(r *http.Request, isAuthenticated bool) bool { @@ -24,22 +27,31 @@ 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 + } + + if path != "/" { + path = strings.TrimSuffix(path, "/") + } + + if result, found := a.cache[path]; found { + return result + } + for _, pattern := range a.IgnorePatterns { - path := r.URL.Path - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - - if path != "/" { - path = strings.TrimSuffix(path, "/") - } - match, _ := doublestar.Match(pattern, path) if match { + a.cache[path] = false return false } } + a.cache[path] = true return true } @@ -65,5 +77,6 @@ func New(cfg *config.Config) (*AutoLogin, error) { return &AutoLogin{ Enabled: cfg.AutoLogin, IgnorePatterns: patterns, + cache: make(map[string]bool), }, nil }