Add caching to minimize lookup time (closes #12)
This commit is contained in:
parent
177f378715
commit
ec76d2b728
3 changed files with 47 additions and 10 deletions
|
@ -3,6 +3,7 @@ package api_v1
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.ar21.de/yolokube/country-geo-locations/pkg/geoloc"
|
"git.ar21.de/yolokube/country-geo-locations/pkg/geoloc"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
@ -49,16 +50,20 @@ func searchIPCtx(next http.Handler) http.Handler {
|
||||||
render.Render(w, r, errInvalidRequest(err))
|
render.Render(w, r, errInvalidRequest(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
for {
|
|
||||||
ipinfo, err = geoloc.SearchIPNet(ipnetnum)
|
newipnet, found := geoloc.IPCache.Get(ipnetnum)
|
||||||
if err != nil {
|
if found {
|
||||||
render.Render(w, r, errNotFound)
|
ipnetnum = newipnet
|
||||||
return
|
}
|
||||||
}
|
|
||||||
if ipinfo != nil {
|
ipinfo, err = geoloc.SearchIPNet(ipnetnum)
|
||||||
break
|
if err != nil {
|
||||||
}
|
render.Render(w, r, errNotFound)
|
||||||
ipnetnum = ipnetnum - 8
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
geoloc.IPCache.Set(ipnetnum, ipinfo.IPNumFrom, 2*time.Minute)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ctx := context.WithValue(r.Context(), keyIPInfo, ipinfo)
|
ctx := context.WithValue(r.Context(), keyIPInfo, ipinfo)
|
||||||
|
|
3
main.go
3
main.go
|
@ -32,6 +32,9 @@ 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)
|
||||||
|
|
29
pkg/geoloc/cache.go
Normal file
29
pkg/geoloc/cache.go
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
package geoloc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var IPCache *Cache
|
||||||
|
|
||||||
|
type Cache struct {
|
||||||
|
store sync.Map
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCache() *Cache {
|
||||||
|
return &Cache{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Cache) Set(key, value uint, ttl time.Duration) {
|
||||||
|
c.store.Store(key, value)
|
||||||
|
time.AfterFunc(ttl, func() {
|
||||||
|
c.store.Delete(key)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Cache) Get(key uint) (uint, bool) {
|
||||||
|
output, _ := c.store.Load(key)
|
||||||
|
value, ok := output.(uint)
|
||||||
|
return value, ok
|
||||||
|
}
|
Loading…
Reference in a new issue