2024-07-28 01:59:58 -04:00
|
|
|
package geoip
|
|
|
|
|
|
|
|
import (
|
2024-10-30 15:34:25 -04:00
|
|
|
_ "embed"
|
2024-07-28 01:59:58 -04:00
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"strings"
|
2024-11-22 09:40:43 -05:00
|
|
|
"sync"
|
2024-07-28 01:59:58 -04:00
|
|
|
|
|
|
|
maxminddb "github.com/oschwald/maxminddb-golang"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed geoip.db
|
2024-10-30 15:34:25 -04:00
|
|
|
var db []byte
|
2024-07-28 01:59:58 -04:00
|
|
|
|
2024-11-22 09:40:43 -05:00
|
|
|
var (
|
|
|
|
dbOnce = sync.OnceValues(func() (*maxminddb.Reader, error) {
|
|
|
|
db, err := maxminddb.FromBytes(db)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return db, nil
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
2024-07-28 01:59:58 -04:00
|
|
|
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) {
|
2024-11-22 09:40:43 -05:00
|
|
|
db, err := dbOnce()
|
2024-07-28 01:59:58 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2024-10-30 15:34:25 -04:00
|
|
|
var record IPInfo
|
|
|
|
err = db.Lookup(ip, &record)
|
2024-07-28 01:59:58 -04:00
|
|
|
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")
|
|
|
|
}
|