Add caching to minimize lookup time (closes #12)

This commit is contained in:
Tom Neuber 2024-02-26 09:40:34 +01:00
parent 177f378715
commit ec76d2b728
3 changed files with 47 additions and 10 deletions

View file

@ -3,6 +3,7 @@ package api_v1
import (
"context"
"net/http"
"time"
"git.ar21.de/yolokube/country-geo-locations/pkg/geoloc"
"github.com/go-chi/chi/v5"
@ -49,16 +50,20 @@ func searchIPCtx(next http.Handler) http.Handler {
render.Render(w, r, errInvalidRequest(err))
return
}
for {
ipinfo, err = geoloc.SearchIPNet(ipnetnum)
if err != nil {
render.Render(w, r, errNotFound)
return
}
if ipinfo != nil {
break
}
ipnetnum = ipnetnum - 8
newipnet, found := geoloc.IPCache.Get(ipnetnum)
if found {
ipnetnum = newipnet
}
ipinfo, err = geoloc.SearchIPNet(ipnetnum)
if err != nil {
render.Render(w, r, errNotFound)
return
}
if !found {
geoloc.IPCache.Set(ipnetnum, ipinfo.IPNumFrom, 2*time.Minute)
}
}
ctx := context.WithValue(r.Context(), keyIPInfo, ipinfo)