mirror of
https://github.com/Buriburizaem0n/nezha_domains.git
synced 2026-02-05 13:10:07 +00:00
feat: use embed geoip database (#396)
* feat: use embed geoip database * mention ipinfo * only read once * comments comments * chore: installer version --------- Co-authored-by: naiba <hi@nai.ba>
This commit is contained in:
1
pkg/geoip/geoip.db
Normal file
1
pkg/geoip/geoip.db
Normal file
@@ -0,0 +1 @@
|
||||
stub
|
||||
54
pkg/geoip/geoip.go
Normal file
54
pkg/geoip/geoip.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package geoip
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
maxminddb "github.com/oschwald/maxminddb-golang"
|
||||
)
|
||||
|
||||
//go:embed geoip.db
|
||||
var geoDBFS embed.FS
|
||||
|
||||
var (
|
||||
dbData []byte
|
||||
err error
|
||||
)
|
||||
|
||||
type IPInfo struct {
|
||||
Country string `maxminddb:"country"`
|
||||
CountryName string `maxminddb:"country_name"`
|
||||
Continent string `maxminddb:"continent"`
|
||||
ContinentName string `maxminddb:"continent_name"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
dbData, err = geoDBFS.ReadFile("geoip.db")
|
||||
if err != nil {
|
||||
log.Printf("NEZHA>> Failed to open geoip database: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Lookup(ip net.IP, record *IPInfo) (string, error) {
|
||||
db, err := maxminddb.FromBytes(dbData)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
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")
|
||||
}
|
||||
Reference in New Issue
Block a user