nezha/pkg/geoip/geoip.go

53 lines
930 B
Go
Raw Normal View History

package geoip
import (
2024-10-30 15:34:25 -04:00
_ "embed"
"fmt"
"net"
"strings"
"sync"
maxminddb "github.com/oschwald/maxminddb-golang"
)
//go:embed geoip.db
2024-10-30 15:34:25 -04:00
var db []byte
var (
dbOnce = sync.OnceValues(func() (*maxminddb.Reader, error) {
db, err := maxminddb.FromBytes(db)
if err != nil {
return nil, err
}
return db, nil
})
)
type IPInfo struct {
Country string `maxminddb:"country"`
CountryName string `maxminddb:"country_name"`
Continent string `maxminddb:"continent"`
ContinentName string `maxminddb:"continent_name"`
}
2024-10-30 15:34:25 -04:00
func Lookup(ip net.IP) (string, error) {
db, err := dbOnce()
if err != nil {
return "", err
}
2024-10-30 15:34:25 -04:00
var record IPInfo
err = db.Lookup(ip, &record)
if err != nil {
return "", err
}
if record.Country != "" {
return strings.ToLower(record.Country), nil
} else if record.Continent != "" {
return strings.ToLower(record.Continent), nil
}
return "", fmt.Errorf("IP not found")
}