perf(handler/autologin): cache NeedsLogin results

This commit is contained in:
Trong Huu Nguyen
2023-01-04 15:46:08 +01:00
parent bd53417f8b
commit 07fc0e24dd

View File

@@ -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
}