/
geo.go
42 lines (37 loc) · 929 Bytes
/
geo.go
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
39
40
41
42
/**
* Copyright 2014 @ z3q.net.
* name : geo.go
* author : jarryliu
* date : 2013-12-02 21:34
* description :
* history :
*/
package tool
//todo: 新浪ip接口,http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=110.110.110.110
import (
"golang.org/x/text/encoding/simplifiedchinese"
"io/ioutil"
"net/http"
"regexp"
)
var (
ip138Regex = regexp.MustCompile("<li>本站主数据:\\s*(.+?)\\s*</li>")
)
func GetLocation(ip string) string {
rsp, err := http.Get("http://www.ip138.com/ips1388.asp?ip=" + ip + "&action=2")
if err != nil {
return "未知地区"
}
data, _ := ioutil.ReadAll(rsp.Body)
out := make([]byte, len(data)*2)
trans := simplifiedchinese.GB18030.NewDecoder()
n, _, err := trans.Transform(out, data, true)
m := ip138Regex.FindAllSubmatch(out[:n], 1)
if len(m) != 0 {
addr := string(m[0][1])
if addr != "保留地址" {
return addr
}
}
return "本地网络"
}