mirror of
https://github.com/skidoodle/ipinfo.git
synced 2025-02-15 08:29:17 +01:00
Refactor IP data lookup with caching
This commit is contained in:
parent
d3dedaa49b
commit
ff2dee80ee
1 changed files with 26 additions and 3 deletions
27
iputils.go
27
iputils.go
|
@ -7,6 +7,8 @@ import (
|
|||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var bogonNets = []*net.IPNet{
|
||||
|
@ -91,8 +93,25 @@ func getRealIP(r *http.Request) string {
|
|||
}
|
||||
}
|
||||
|
||||
// Lookup IP data in the databases
|
||||
var ipCache = sync.Map{}
|
||||
|
||||
type cachedIPData struct {
|
||||
data *dataStruct
|
||||
time time.Time
|
||||
}
|
||||
|
||||
const cacheTTL = time.Minute * 10
|
||||
|
||||
// Lookup IP data in the databases with caching
|
||||
func lookupIPData(ip net.IP) *dataStruct {
|
||||
if cachedData, ok := ipCache.Load(ip.String()); ok {
|
||||
cached := cachedData.(cachedIPData)
|
||||
if time.Since(cached.time) < cacheTTL {
|
||||
return cached.data
|
||||
}
|
||||
ipCache.Delete(ip.String())
|
||||
}
|
||||
|
||||
dbMtx.RLock()
|
||||
defer dbMtx.RUnlock()
|
||||
|
||||
|
@ -144,7 +163,7 @@ func lookupIPData(ip net.IP) *dataStruct {
|
|||
sd = &name
|
||||
}
|
||||
|
||||
return &dataStruct{
|
||||
data := &dataStruct{
|
||||
IP: toPtr(ip.String()),
|
||||
Hostname: toPtr(strings.TrimSuffix(hostname[0], ".")),
|
||||
ASN: toPtr(fmt.Sprintf("%d", asnRecord.AutonomousSystemNumber)),
|
||||
|
@ -156,6 +175,10 @@ func lookupIPData(ip net.IP) *dataStruct {
|
|||
Timezone: toPtr(cityRecord.Location.Timezone),
|
||||
Loc: toPtr(fmt.Sprintf("%.4f,%.4f", cityRecord.Location.Latitude, cityRecord.Location.Longitude)),
|
||||
}
|
||||
|
||||
ipCache.Store(ip.String(), cachedIPData{data: data, time: time.Now()})
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
// Convert string to pointer
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue