-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountry.go
51 lines (40 loc) · 853 Bytes
/
country.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
package country_ip
import (
"errors"
"net"
)
func init() {
initDB()
}
var (
// CN represents China
CN = NewCountry("CN")
// ErrCountryNotFound determins the given country dose not exit in list
// https://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest
ErrCountryNotFound = errors.New("country not found")
)
type Country interface {
// Has checks if country's CIDR contains given ip
Has(string) (bool, error)
// String returns country's name
String() string
}
func NewCountry(c string) Country {
return country(c)
}
type country string
func (c country) Has(ip string) (bool, error) {
r, ok := mCidr[c]
if !ok {
return false, ErrCountryNotFound
}
i := net.ParseIP(ip)
return r.Contains(i)
}
func (c country) String() string {
return string(c)
}
// List returns countries names
func List() []string {
return cList
}