-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
61 lines (50 loc) · 1 KB
/
db.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
package geoip
import (
"log"
"net"
"strings"
"time"
"github.com/oschwald/maxminddb-golang"
)
// nil, if database not loaded
var db *maxminddb.Reader
var NY *time.Location
func init() {
NY, _ = time.LoadLocation("America/New_York")
}
func Load() error {
var err error
db, err = maxminddb.Open("GeoLite2-Country.mmdb")
if err != nil {
db = nil
}
return nil
}
// Look up the country ISO code of the IP
func LookUp(ip string) (iso string) {
// DB not loaded
if db == nil {
return
}
// All IPs, that make it till here should be valid, but best be safe
dec := net.ParseIP(ip)
if dec == nil {
return
}
var record struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
} `maxminddb:"country"`
}
if err := db.Lookup(dec, &record); err != nil {
log.Printf("country lookup for `%s`: %s", ip, err)
}
iso = strings.ToLower(record.Country.ISOCode)
if iso == "us" && NY != nil {
t := time.Now().In(NY)
if t.Month() == time.July && t.Day() == 4 {
iso = "il"
}
}
return
}