前言
最近接手公司go后台的项目,遇到了一个获取IP归属地的需求。需求还是比较简单的,写一个接口,前端在调用的时候把IP地址传给我,我返回给他IP归属地相关信息。
探索
首先还是了解一下IP归属地:IP地址归属地指的是与IP地址相关的地理位置信息。这通常包括国家、城市、经纬度等,IP地址与地理位置的映射表是不断变化的。
想要获取到相关信息最好的方式还是选用第三方API,对此我通过以下几个方面对多个服务商进行了调研和筛选:
1.价格:成本方面是第一位的,一般API都是按照调用次数进行收费。
2.精度、准确度:我这次的需求需要精确到街道级的数据精度,所以在选用的时候一定要看清楚API提供的数据精度,最好是能够免费测试,避免浪费后续的财力、人力和时间。
3.开发成本:身为一个开发人员,在接入三方的时候最希望的就是接入方式简单名了,文档清晰易懂,最好是有客服能够提供技术支持。
4.稳定:不同服务商返回的数据有所差异,所以在选用的时候最好是挑选有实力的大厂商,以免出现更换服务商的情况。
基于上述几点和一定数量的测试后,我最终选用了IP数据云进行开发。
开发
开发的过程还是比较容易上手的,下面我贴一下项目中的代码片段以供参考:
type IpInfos struct {
AreaCode string json:"area_code"
//行政区码
City string json:"city"
//城市
CityCode string json:"city_code"
//城市代码
Continent string json:"continent"
//洲
Country string json:"country"
//国家/地区
CountryCode string json:"country_code"
//国家/地区英文简写
District string json:"district"
//区县
Elevation string json:"elevation"
//海拔
Ip string json:"ip"
//ip地址
Isp string json:"isp"
//运营商
Latitude string json:"latitude"
//纬度
Longitude string json:"longitude"
//经度
MultiStreet []Street json:"multi_street"
//历史街道位置
Province string json:"province"
//省份
Street string json:"street"
//街道
TimeZone string json:"time_zone"
//时区
WeatherStation string json:"weather_station"
//气象站
ZipCode string json:"zip_code"
//邮编
}
type Street struct {
Lng string json:"lng"
//经度
Lat string json:"lat"
//纬度
Province string json:"province"
//省份
City string json:"city"
//城市
District string json:"district"
//区县
Street string json:"street"
//街道
Radius string json:"radius"
//半径
ZipCode string json:"zip_code"
//邮政编码
}
// GetIpInfo 获取IP归属地
func GetIpInfo(c *gin.Context) {
ip := c.DefaultPostForm(“ip”, “”)
if ip == “” {
util.JsonReturn(c, util.ERROR, “请输入ip”)
return
}
url := “https://api.ipdatacloud.com/v2/query?ip=” + ip + “key=”//拼接申请的key
resp, err := http.Get(url)
if err != nil {
util.JsonReturn(c, util.ERROR, err.Error())
return
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode > 299 {
util.JsonReturn(c, util.ERROR, strconv.Itoa(resp.StatusCode))
return
}
if err != nil {
util.JsonReturn(c, util.ERROR, err.Error())
return
}
bodyStr := string(body)
//对返回的json数据做解析
var dataJson map[string]interface{}
err = json.Unmarshal([]byte(bodyStr), &dataJson)
modelJson := dataJson[“data”].(map[string]interface{})
locationByte, err := json.Marshal(modelJson[“location”])
var info = IpInfos{}
err = json.Unmarshal(locationByte, &info)
if err != nil {
util.JsonReturn(c, util.ERROR, err.Error())
return
}
util.JsonpReturnData(c, util.SUCCESS, “ip归属地信息”, info)
}
总结
项目已经运行一段时间,目前IP数据云API的使用很稳定,如果这篇文章对您有所帮助,或者有所启发的话,求点赞、评论、收藏+关注,您的支持是我坚持写作最大的动力。