mirror of
https://github.com/yusing/godoxy.git
synced 2026-04-28 11:17:09 +02:00
Remove the xsync map cache and add a 1000-entry goutils keyed cache in lookup.go. Rrate-limit failure logs, and populate IPInfo.City. Adjust ACL Geo matchers to the new signature.
41 lines
829 B
Go
41 lines
829 B
Go
package maxmind
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
|
|
"github.com/yusing/goutils/cache"
|
|
)
|
|
|
|
var ErrInvalidIP = errors.New("invalid IP address")
|
|
var ErrDBNotLoaded = errors.New("maxmind database not loaded")
|
|
|
|
var lookupCityFn = cache.NewKeyFunc(func(_ context.Context, ipStr string) (*City, error) {
|
|
return instance.lookupCityReal(ipStr)
|
|
}).WithMaxEntries(1000).Build()
|
|
|
|
func lookupCityNoContext(ipStr string) (*City, error) {
|
|
return lookupCityFn(context.Background(), ipStr)
|
|
}
|
|
|
|
func (cfg *MaxMind) lookupCityReal(ipStr string) (*City, error) {
|
|
cfg.db.RLock()
|
|
defer cfg.db.RUnlock()
|
|
|
|
if cfg.db.Reader == nil {
|
|
return nil, ErrDBNotLoaded
|
|
}
|
|
|
|
city := new(City)
|
|
ip := net.ParseIP(ipStr)
|
|
if ip == nil {
|
|
return nil, ErrInvalidIP
|
|
}
|
|
err := cfg.db.Lookup(ip, city)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return city, nil
|
|
}
|