-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip2loc.go
More file actions
79 lines (70 loc) · 1.68 KB
/
Copy pathip2loc.go
File metadata and controls
79 lines (70 loc) · 1.68 KB
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
79
package finder
import (
"github.com/lionsoul2014/ip2region/binding/golang/ip2region"
"github.com/phuslu/log"
)
/////////////////////////////
// IP2Location Finder Result
/////////////////////////////
type IP2LocResult struct {
IP string `json:"ip"`
CityId int64 `json:"city_id"`
Country string `json:"country"`
Region string `json:"region"`
Province string `json:"province"`
City string `json:"city"`
ISP string `json:"isp"`
}
//func (ip2lr IP2LocResult) Json() string {
// body, _ := json.Marshal(ip2lr)
// return string(body)
//}
/////////////////////////////
// IP2Location Finder
/////////////////////////////
type IP2LocFinder struct {
engine *ip2region.Ip2Region
}
func NewIP2LocFinder(db string) *IP2LocFinder {
engine, err := ip2region.New(db)
if err != nil {
log.Fatal().Msgf("init ip2region db:%s, err: %s", db, err)
}
return &IP2LocFinder{engine}
}
func (iplf *IP2LocFinder) Find(ip string, algorithm string) (*IP2LocResult, error) {
var ipInfo ip2region.IpInfo
var err error
switch algorithm {
case "binary":
ipInfo, err = iplf.engine.BinarySearch(ip)
break
case "btree":
ipInfo, err = iplf.engine.BtreeSearch(ip)
break
case "memory":
ipInfo, err = iplf.engine.MemorySearch(ip)
break
default:
ipInfo, err = iplf.engine.MemorySearch(ip)
}
if err == nil {
return &IP2LocResult{
IP: ip,
CityId: ipInfo.CityId,
Country: ipInfo.Country,
Region: ipInfo.Region,
Province: ipInfo.Province,
City: ipInfo.City,
ISP: ipInfo.ISP,
}, err
} else {
return nil, err
}
}
func (iplf *IP2LocFinder) Close() {
iplf.engine.Close()
}
func (iplf *IP2LocFinder) Version() string {
return "ip2region@v2.2.0"
}