2021-09-29 14:44:47 +08:00
|
|
|
|
package tipdw
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io/ioutil"
|
|
|
|
|
"net/http"
|
2021-09-30 12:55:34 +08:00
|
|
|
|
"sync"
|
2021-09-29 14:44:47 +08:00
|
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
2021-09-30 12:55:34 +08:00
|
|
|
|
var (
|
|
|
|
|
client = &http.Client{Timeout: 5 * time.Second}
|
|
|
|
|
ipCache = &sync.Map{}
|
|
|
|
|
)
|
2021-09-29 14:44:47 +08:00
|
|
|
|
|
|
|
|
|
type Body struct {
|
2021-09-29 15:50:34 +08:00
|
|
|
|
Status int `json:"status"` // 状态码,0为正常,其它为异常
|
|
|
|
|
Message string `json:"message"` // 对status的描述
|
|
|
|
|
Result Result `json:"result"` // IP定位结果
|
2021-09-29 14:44:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type Result struct {
|
2021-09-29 15:50:34 +08:00
|
|
|
|
IP string `json:"ip"` // 用于定位的IP地址
|
|
|
|
|
AdInfo AdInfo `json:"ad_info"` // 定位行政区划信息
|
|
|
|
|
Location Location `json:"location"` // 定位坐标
|
2021-09-29 14:44:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type AdInfo struct {
|
2021-09-29 15:50:34 +08:00
|
|
|
|
Nation string `json:"nation"` // 国家
|
|
|
|
|
Province string `json:"province"` // 省
|
|
|
|
|
City string `json:"city"` // 市
|
|
|
|
|
District string `json:"district"` // 区
|
|
|
|
|
Adcode int `json:"adcode"` // 行政区划代码
|
2021-09-29 14:44:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type Location struct {
|
2021-09-29 15:50:34 +08:00
|
|
|
|
Lat float64 `json:"lat"` // 纬度
|
|
|
|
|
Lng float64 `json:"lng"` // 经度
|
2021-09-29 14:44:47 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// QueryIP 使用腾讯位置服务查询IP
|
2021-09-30 11:08:35 +08:00
|
|
|
|
func QueryIP(sk string, key string, ip string) (result Result, err error) {
|
2021-09-30 12:55:34 +08:00
|
|
|
|
v, ok := ipCache.Load(ip)
|
|
|
|
|
if ok {
|
|
|
|
|
result = v.(Result)
|
|
|
|
|
return
|
|
|
|
|
}
|
2021-09-29 14:44:47 +08:00
|
|
|
|
arg := &reqLBS{
|
|
|
|
|
SK: sk,
|
|
|
|
|
Path: "/ws/location/v1/ip",
|
|
|
|
|
Args: map[string]string{
|
|
|
|
|
"ip": ip,
|
|
|
|
|
"key": key,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s?%s", "https://apis.map.qq.com/ws/location/v1/ip", arg.Encode()), nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
var bodyUnmarshal Body
|
|
|
|
|
err = json.Unmarshal(body, &bodyUnmarshal)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if bodyUnmarshal.Status != 0 {
|
|
|
|
|
err = fmt.Errorf("resp code is %d, body is %s", bodyUnmarshal.Status, body)
|
|
|
|
|
return
|
|
|
|
|
}
|
2021-09-30 11:08:35 +08:00
|
|
|
|
result = bodyUnmarshal.Result
|
2021-09-30 12:55:34 +08:00
|
|
|
|
ipCache.Store(ip, bodyUnmarshal.Result)
|
2021-09-29 14:44:47 +08:00
|
|
|
|
return
|
|
|
|
|
}
|