package common import ( "context" "fmt" "net" "stat/common/httputil" "stat/common/log" "time" ) var ( defaultCity = "广州" defaultProvince = "广东" ipNewURL = "https://loc.ztgba.com/self/getLocationByIp" ipNewURLV2 = "https://loc.ztgba.com/self/isChina" NoChina int32 = 0 ) //老接口 type LocationResp struct { RegionName string `json:"region_name"` CityName string `json:"city_name"` IP string `json:"ip"` } func GetLocationByIP(ip string) (string, string) { //return defaultCity, defaultProvince var params = map[string]string{"ip": ip} loc := LocationResp{} c, cancle := context.WithTimeout(context.Background(), 3*time.Second) defer cancle() _, err := httputil.NewCtx(c).POSTJsonWithJResp(&loc, ipNewURL, nil, params) if err != nil { log.Error("GetLocationByIP error", log.Any("ip", ip), log.Any("err", err)) return defaultCity, defaultProvince } Go(func() { select { case <-c.Done(): fmt.Print("current http method GetLocationByIP ctx", c.Err()) } }) if len(loc.RegionName) == 0 && len(loc.CityName) == 0 { return defaultCity, defaultProvince } if loc.RegionName == "局域网" { return defaultCity, defaultProvince } if loc.RegionName == "柬埔寨" { return defaultCity, defaultProvince } if len(loc.CityName) == 0 { return loc.RegionName, loc.RegionName } return loc.CityName, loc.RegionName } type CountryResp struct { Country string `json:"country_name"` RegionName string `json:"region_name"` IP string `json:"ip"` } type CountryRespV2 struct { Code int32 `json:"code"` Data map[string]int32 `json:"data"` } //InChina //香港返回false func InChina(ip string) bool { var params = map[string]string{"ip": ip} resp := CountryResp{} _, err := httputil.New().POSTJsonWithJResp(&resp, ipNewURL, nil, params) if err != nil { log.Error("InChina error", log.Any("ip", ip), log.Any("err", err)) return true } if resp.RegionName == "香港" { return false } return resp.Country == "中国" } func GetLocalIP() string { addrs, err := net.InterfaceAddrs() if err != nil { return "" } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil && ipnet.IP.IsGlobalUnicast() { return ipnet.IP.String() } } } return "" } func InChinaV2(ip string) bool { var params = map[string]string{"ip": ip} resp := CountryRespV2{} _, err := httputil.New().GetWithJResp(&resp, ipNewURLV2, nil, params) if err != nil { log.Error("InChina error", log.Any("ip", ip), log.Any("err", err)) return true } if value, ok := resp.Data[ip]; ok { return value != NoChina } return false }