Adjust cache to private variable

This commit is contained in:
Tom Neuber 2024-03-02 11:48:53 +01:00
parent 41605f743a
commit 20b21c0221
Signed by: tom
GPG key ID: F17EFE4272D89FF6
3 changed files with 24 additions and 6 deletions

View file

@ -51,7 +51,7 @@ func searchIPCtx(next http.Handler) http.Handler {
return return
} }
newipnet, found := geoloc.IPCache.Get(ipnetnum) newipnet, found := geoloc.GetCacheContent(ipnetnum)
if found { if found {
ipnetnum = newipnet ipnetnum = newipnet
} }
@ -63,7 +63,7 @@ func searchIPCtx(next http.Handler) http.Handler {
} }
if !found { if !found {
geoloc.IPCache.Set(ipnetnum, ipinfo.IPNumFrom, 2*time.Minute) geoloc.SetCacheContent(ipnetnum, ipinfo.IPNumFrom, 2*time.Minute)
} }
} }
ctx := context.WithValue(r.Context(), keyIPInfo, ipinfo) ctx := context.WithValue(r.Context(), keyIPInfo, ipinfo)

View file

@ -41,9 +41,6 @@ func main() {
} }
fmt.Println("Import data from file successful") fmt.Println("Import data from file successful")
geoloc.IPCache = geoloc.NewCache()
fmt.Println("Cache created")
r := chi.NewRouter() r := chi.NewRouter()
r.Use(middleware.RequestID) r.Use(middleware.RequestID)
r.Use(middleware.Logger) r.Use(middleware.Logger)

View file

@ -5,7 +5,7 @@ import (
"time" "time"
) )
var IPCache *Cache var ipCache *Cache
type Cache struct { type Cache struct {
store sync.Map store sync.Map
@ -27,3 +27,24 @@ func (c *Cache) Get(key uint) (uint, bool) {
value, ok := output.(uint) value, ok := output.(uint)
return value, ok return value, ok
} }
func createCache() {
ipCache = NewCache()
}
func GetCacheContent(key uint) (uint, bool) {
if ipCache == nil {
createCache()
return 0, false
}
return ipCache.Get(key)
}
func SetCacheContent(key, value uint, ttl time.Duration) {
if ipCache == nil {
createCache()
}
ipCache.Set(key, value, ttl)
}