zhangzengfei
2022-01-19 2a866b08f0efcb886e09cf4418888434dcb6e593
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package iploc
 
import (
    "encoding/json"
    "net/http"
)
 
const IP_API_URL = "http://ip-api.com/json/"
 
// Data from ip-api.com
type GeoIP struct {
    InternetIp string  `json:"query"`      // 外网ip
    Country    string  `json:"country"`    // 国家
    RegionName string  `json:"regionName"` // 地区
    City       string  `json:"city"`       // 城市
    Lat        float64 `json:"lat"`
    Lon        float64 `json:"lon"`
}
 
func GetLocation() (geo GeoIP, err error) {
    return GetLocationForIp("")
}
 
// Geoloc an IP address, return city + country
func GetLocationForIp(addr string) (geo GeoIP, err error) {
    resp, err := http.Get(IP_API_URL + addr + "?lang=zh-CN")
    if err != nil {
        return
    }
    defer resp.Body.Close()
 
    err = json.NewDecoder(resp.Body).Decode(&geo)
    if err != nil {
        return
    }
 
    return geo, nil
}