From 20b21c0221a4410b77f01d18caaa3995e29fcedb Mon Sep 17 00:00:00 2001 From: Tom Neuber Date: Sat, 2 Mar 2024 11:48:53 +0100 Subject: [PATCH] Adjust cache to private variable --- api/v1/server.go | 4 ++-- main.go | 3 --- pkg/geoloc/cache.go | 23 ++++++++++++++++++++++- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/api/v1/server.go b/api/v1/server.go index 73052e7..c99e39e 100644 --- a/api/v1/server.go +++ b/api/v1/server.go @@ -51,7 +51,7 @@ func searchIPCtx(next http.Handler) http.Handler { return } - newipnet, found := geoloc.IPCache.Get(ipnetnum) + newipnet, found := geoloc.GetCacheContent(ipnetnum) if found { ipnetnum = newipnet } @@ -63,7 +63,7 @@ func searchIPCtx(next http.Handler) http.Handler { } 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) diff --git a/main.go b/main.go index f1f9df5..5dce4bc 100644 --- a/main.go +++ b/main.go @@ -41,9 +41,6 @@ func main() { } fmt.Println("Import data from file successful") - geoloc.IPCache = geoloc.NewCache() - fmt.Println("Cache created") - r := chi.NewRouter() r.Use(middleware.RequestID) r.Use(middleware.Logger) diff --git a/pkg/geoloc/cache.go b/pkg/geoloc/cache.go index 6b29b9d..fbec684 100644 --- a/pkg/geoloc/cache.go +++ b/pkg/geoloc/cache.go @@ -5,7 +5,7 @@ import ( "time" ) -var IPCache *Cache +var ipCache *Cache type Cache struct { store sync.Map @@ -27,3 +27,24 @@ func (c *Cache) Get(key uint) (uint, bool) { value, ok := output.(uint) 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) +}