mirror of
https://github.com/Buriburizaem0n/nezha_domains.git
synced 2026-02-04 04:30:05 +00:00
💩 优化 CountryCode 获取
This commit is contained in:
@@ -12,9 +12,23 @@ import (
|
||||
)
|
||||
|
||||
type geoIP struct {
|
||||
CountryCode string `json:"country_code,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Query string `json:"query,omitempty"`
|
||||
CountryCode string `json:"country_code,omitempty"`
|
||||
CountryCode2 string `json:"countryCode,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Query string `json:"query,omitempty"`
|
||||
}
|
||||
|
||||
func (ip *geoIP) Unmarshal(body []byte) error {
|
||||
if err := utils.Json.Unmarshal(body, ip); err != nil {
|
||||
return err
|
||||
}
|
||||
if ip.IP == "" && ip.Query != "" {
|
||||
ip.IP = ip.Query
|
||||
}
|
||||
if ip.CountryCode == "" && ip.CountryCode2 != "" {
|
||||
ip.CountryCode = ip.CountryCode2
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -23,7 +37,7 @@ var (
|
||||
"https://ipapi.co/json",
|
||||
"https://freegeoip.app/json/",
|
||||
"http://ip-api.com/json/",
|
||||
"https://extreme-ip-lookup.com/json/",
|
||||
// "https://extreme-ip-lookup.com/json/",
|
||||
// "https://ip.seeip.org/geoip",
|
||||
}
|
||||
cachedIP, cachedCountry string
|
||||
@@ -70,13 +84,9 @@ func fetchGeoIP(servers []string, isV6 bool) geoIP {
|
||||
return ip
|
||||
}
|
||||
resp.Body.Close()
|
||||
err = utils.Json.Unmarshal(body, &ip)
|
||||
if err != nil {
|
||||
if err := ip.Unmarshal(body); err != nil {
|
||||
return ip
|
||||
}
|
||||
if ip.IP == "" && ip.Query != "" {
|
||||
ip.IP = ip.Query
|
||||
}
|
||||
// 没取到 v6 IP
|
||||
if isV6 && !strings.Contains(ip.IP, ":") {
|
||||
return ip
|
||||
|
||||
@@ -17,14 +17,16 @@ func TestGeoIPApi(t *testing.T) {
|
||||
assert.Nil(t, err)
|
||||
resp.Body.Close()
|
||||
var ip geoIP
|
||||
err = utils.Json.Unmarshal(body, &ip)
|
||||
err = ip.Unmarshal(body)
|
||||
assert.Nil(t, err)
|
||||
t.Logf("%s %s %s %s", geoIPApiList[i], ip.CountryCode, utils.IPDesensitize(ip.IP), utils.IPDesensitize(ip.Query))
|
||||
assert.True(t, ip.IP != "" || ip.Query != "")
|
||||
t.Logf("%s %s %s", geoIPApiList[i], ip.CountryCode, utils.IPDesensitize(ip.IP))
|
||||
assert.True(t, ip.IP != "")
|
||||
assert.True(t, ip.CountryCode != "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchGeoIP(t *testing.T) {
|
||||
ip := fetchGeoIP(geoIPApiList, false)
|
||||
assert.NotEmpty(t, ip.IP)
|
||||
assert.NotEmpty(t, ip.CountryCode)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user