84 lines
1.6 KiB
Go
84 lines
1.6 KiB
Go
package geo
|
|
|
|
import (
|
|
"encoding/json"
|
|
"github.com/pkg/errors"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func Ipapi() (prov, city, isp string, err error) {
|
|
const endpoint = "http://ip-api.com/json/?fields=regionName,city,as&lang=zh-CN"
|
|
|
|
resp, err := http.Get(endpoint)
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "", "", "", err
|
|
}
|
|
|
|
var data struct {
|
|
RegionName string `json:"regionName"`
|
|
City string `json:"city"`
|
|
As string `json:"as"`
|
|
}
|
|
err = json.NewDecoder(resp.Body).Decode(&data)
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
prov = data.RegionName
|
|
city = data.City
|
|
|
|
var telecom = []string{"AS4134", "AS4812", "AS134419", "AS140292"}
|
|
var unicom = []string{"AS4837", "AS17621", "AS17816"}
|
|
var mobile = []string{
|
|
"AS9808", "AS24444", "AS24445", "AS24547", "AS38019",
|
|
"AS56040", "AS56041", "AS56042", "AS56044", "AS56046", "AS56047",
|
|
"AS132525", "AS134810",
|
|
}
|
|
var foreign = []string{
|
|
"AS9299",
|
|
}
|
|
|
|
for _, telecomAsn := range telecom {
|
|
if strings.HasPrefix(data.As, telecomAsn) {
|
|
isp = "电信"
|
|
break
|
|
}
|
|
}
|
|
if isp == "" {
|
|
for _, unicomAsn := range unicom {
|
|
if strings.HasPrefix(data.As, unicomAsn) {
|
|
isp = "联通"
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if isp == "" {
|
|
for _, mobileAsn := range mobile {
|
|
if strings.HasPrefix(data.As, mobileAsn) {
|
|
isp = "移动"
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if isp == "" {
|
|
for _, foreignAsn := range foreign {
|
|
if strings.HasPrefix(data.As, foreignAsn) {
|
|
isp = "国外"
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if prov == "" || city == "" || isp == "" {
|
|
return "", "", "", errors.New("解析数据为空")
|
|
}
|
|
|
|
return prov, city, isp, nil
|
|
}
|