mirror of
https://github.com/nezhahq/nezha.git
synced 2025-01-22 12:48:14 -05:00
fc98c0919f
* new geoip method * report geoip separately, fix server creation & deletion bugs * fix struct tag * fix write name * remove deleteion list * remove rpc realip header * Revert "remove rpc realip header" This reverts commit 8a5f86cf2d7df87f28cfa2a3b3430f449dd6ed73.
53 lines
930 B
Go
53 lines
930 B
Go
package geoip
|
|
|
|
import (
|
|
_ "embed"
|
|
"fmt"
|
|
"net"
|
|
"strings"
|
|
"sync"
|
|
|
|
maxminddb "github.com/oschwald/maxminddb-golang"
|
|
)
|
|
|
|
//go:embed geoip.db
|
|
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"`
|
|
}
|
|
|
|
func Lookup(ip net.IP) (string, error) {
|
|
db, err := dbOnce()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
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")
|
|
}
|