💩 优化 CountryCode 获取
This commit is contained in:
parent
1f051459bb
commit
888f2efa60
2
.github/workflows/test.yml
vendored
2
.github/workflows/test.yml
vendored
@ -30,4 +30,4 @@ jobs:
|
||||
- name: Run Gosec Security Scanner
|
||||
run: |
|
||||
go install github.com/securego/gosec/v2/cmd/gosec@latest
|
||||
gosec -exclude=G104 ./...
|
||||
gosec -exclude=G104,G404 ./...
|
||||
|
@ -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)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user