-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathip2country.go
55 lines (45 loc) · 968 Bytes
/
ip2country.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
package ip2country
import (
"embed"
"io"
"net"
"sync"
"github.com/klauspost/compress/zstd"
"github.com/oschwald/maxminddb-golang"
)
var (
//go:embed geolite2-country.mmdb.zst
files embed.FS
loadDB = sync.OnceValues(initDB)
)
// Lookup returns the country (code) in which ip is located, or an error if not found.
func Lookup(ip net.IP) (string, error) {
db, err := loadDB()
if err != nil {
return "", err
}
var record string
err = db.Lookup(ip, &record)
return record, err
}
// LookupString is a wrapper Lookup(net.ParseIP(ip))
func LookupString(ip string) (string, error) {
return Lookup(net.ParseIP(ip))
}
func initDB() (*maxminddb.Reader, error) {
f, err := files.Open("geolite2-country.mmdb.zst")
if err != nil {
return nil, err
}
defer f.Close()
r, err := zstd.NewReader(f)
if err != nil {
return nil, err
}
defer r.Close()
src, err := io.ReadAll(r)
if err != nil {
return nil, err
}
return maxminddb.FromBytes(src)
}