2023-07-14 22:28:24 +08:00
|
|
|
package mmdb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
2024-03-08 22:45:10 +08:00
|
|
|
"strings"
|
2023-07-14 22:28:24 +08:00
|
|
|
|
|
|
|
"github.com/oschwald/maxminddb-golang"
|
|
|
|
)
|
|
|
|
|
|
|
|
type geoip2Country struct {
|
|
|
|
Country struct {
|
|
|
|
IsoCode string `maxminddb:"iso_code"`
|
|
|
|
} `maxminddb:"country"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type Reader struct {
|
|
|
|
*maxminddb.Reader
|
|
|
|
databaseType
|
|
|
|
}
|
|
|
|
|
2023-07-17 10:33:20 +08:00
|
|
|
func (r Reader) LookupCode(ipAddress net.IP) []string {
|
2023-07-14 22:28:24 +08:00
|
|
|
switch r.databaseType {
|
|
|
|
case typeMaxmind:
|
|
|
|
var country geoip2Country
|
|
|
|
_ = r.Lookup(ipAddress, &country)
|
2023-07-17 10:33:20 +08:00
|
|
|
if country.Country.IsoCode == "" {
|
|
|
|
return []string{}
|
|
|
|
}
|
2024-03-08 22:45:10 +08:00
|
|
|
return []string{strings.ToLower(country.Country.IsoCode)}
|
2023-07-14 22:28:24 +08:00
|
|
|
|
|
|
|
case typeSing:
|
|
|
|
var code string
|
|
|
|
_ = r.Lookup(ipAddress, &code)
|
2023-07-17 10:33:20 +08:00
|
|
|
if code == "" {
|
|
|
|
return []string{}
|
|
|
|
}
|
|
|
|
return []string{code}
|
|
|
|
|
|
|
|
case typeMetaV0:
|
|
|
|
var record any
|
|
|
|
_ = r.Lookup(ipAddress, &record)
|
|
|
|
switch record := record.(type) {
|
|
|
|
case string:
|
|
|
|
return []string{record}
|
|
|
|
case []any: // lookup returned type of slice is []any
|
2024-03-02 17:41:04 +08:00
|
|
|
result := make([]string, 0, len(record))
|
|
|
|
for _, item := range record {
|
|
|
|
result = append(result, item.(string))
|
|
|
|
}
|
|
|
|
return result
|
2023-07-17 10:33:20 +08:00
|
|
|
}
|
|
|
|
return []string{}
|
2023-07-14 22:28:24 +08:00
|
|
|
|
|
|
|
default:
|
|
|
|
panic(fmt.Sprint("unknown geoip database type:", r.databaseType))
|
|
|
|
}
|
|
|
|
}
|