-
Notifications
You must be signed in to change notification settings - Fork 0
/
geoip.go
52 lines (45 loc) · 982 Bytes
/
geoip.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
package geoip
import (
"log"
"net/http"
"path/filepath"
"meguca/auth"
"github.com/oschwald/maxminddb-golang"
)
var (
// nil if database not loaded.
db *maxminddb.Reader
)
// NOTE(Kagami): We don't require presence of GetIP database files for a
// moment so in case of any loading errors we will just return empty
// lookup results.
func Load(dir string) error {
dbPath := filepath.Join(dir, "GeoLite2-Country.mmdb")
var err error
db, err = maxminddb.Open(dbPath)
if err != nil {
log.Printf("GeoIP: %v", err)
}
return nil
}
type geoRecord struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
} `maxminddb:"country"`
}
// Get request's country.
func CountyFromReq(r *http.Request) (code string) {
if db == nil {
return
}
ip, err := auth.GetByteIP(r)
if err != nil {
return
}
var rec geoRecord
if err := db.Lookup(ip, &rec); err != nil {
log.Printf("Country lookup error for %v: %v", ip, err)
return
}
return rec.Country.ISOCode
}