-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipip.go
78 lines (69 loc) · 1.36 KB
/
ipip.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package ipip
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/ipipdotnet/ipdb-go"
)
// Global variables
var (
DB *ipdb.City
Language string = "CN"
)
// Open the ipdb file
func Open(file string) (err error) {
if DB == nil {
if file == "" {
file = filepath.Join(getExeDir(), "ipipfree.ipdb")
}
DB, err = ipdb.NewCity(file)
if err != nil {
return
}
}
return
}
// FatalOpen open the ipdb file, if an error occurs the program exit
func FatalOpen(file string) {
if err := Open(file); err != nil {
log.Fatalln(err)
}
}
// Get ip location from ipdb file
func Get(ip string) string {
result, err := DB.Find(ip, Language)
if err != nil {
return ""
}
return trim(result)
}
// APIGet get ip location from free API
func APIGet(ip string) string {
resp, err := http.Get("http://freeapi.ipip.net/" + ip)
if err != nil {
return "<Http Get Error>"
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
result := make([]string, 5)
json.Unmarshal(body, &result)
return trim(result)
}
func trim(result []string) (s string) {
s = result[1]
if s != result[2] {
s = strings.TrimSpace(s + " " + result[2])
}
if result[0] != "中国" && result[0] != s {
s = strings.TrimSpace(result[0] + " " + s)
}
return
}
func getExeDir() string {
s, _ := os.Executable()
return filepath.Dir(s)
}