Improve geoip database downloading and do not block connections
This commit is contained in:
@@ -1,52 +1,26 @@
|
||||
package geoip
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/oschwald/maxminddb-golang"
|
||||
)
|
||||
|
||||
func getReader(ip net.IP) *maxminddb.Reader {
|
||||
if v4 := ip.To4(); v4 != nil {
|
||||
return geoDBv4Reader
|
||||
}
|
||||
return geoDBv6Reader
|
||||
isV6 := ip.To4() == nil
|
||||
return worker.GetReader(isV6, true)
|
||||
}
|
||||
|
||||
// GetLocation returns Location data of an IP address
|
||||
func GetLocation(ip net.IP) (record *Location, err error) {
|
||||
dbLock.RLock()
|
||||
defer dbLock.RUnlock()
|
||||
|
||||
err = prepDatabaseForUse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func GetLocation(ip net.IP) (*Location, error) {
|
||||
db := getReader(ip)
|
||||
|
||||
record = &Location{}
|
||||
|
||||
// fetch
|
||||
err = db.Lookup(ip, record)
|
||||
|
||||
// retry
|
||||
if err != nil {
|
||||
// reprep
|
||||
handleError(err)
|
||||
err = prepDatabaseForUse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db = getReader(ip)
|
||||
|
||||
// refetch
|
||||
err = db.Lookup(ip, record)
|
||||
if db == nil {
|
||||
return nil, fmt.Errorf("geoip database not available")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
var record Location
|
||||
if err := db.Lookup(ip, &record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return record, nil
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user