forked from PostHog/posthog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeoip.go
43 lines (35 loc) · 777 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
package main
import (
"errors"
"net"
"github.com/oschwald/maxminddb-golang"
)
type GeoLocator struct {
db *maxminddb.Reader
}
func NewGeoLocator(dbPath string) (*GeoLocator, error) {
db, err := maxminddb.Open(dbPath)
if err != nil {
return nil, err
}
return &GeoLocator{
db: db,
}, nil
}
func (g *GeoLocator) Lookup(ipString string) (float64, float64, error) {
ip := net.ParseIP(ipString)
if ip == nil {
return 0, 0, errors.New("invalid IP address")
}
var record struct {
Location struct {
Latitude float64 `maxminddb:"latitude"`
Longitude float64 `maxminddb:"longitude"`
} `maxminddb:"location"`
}
err := g.db.Lookup(ip, &record)
if err != nil {
return 0, 0, err
}
return record.Location.Latitude, record.Location.Longitude, nil
}