-
Notifications
You must be signed in to change notification settings - Fork 1
/
types.go
86 lines (75 loc) · 2.01 KB
/
types.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package traefikgeoip2
import (
"fmt"
"net"
"strconv"
"github.com/IncSW/geoip2"
)
// Unknown constant for undefined data.
const Unknown = "XX"
// DefaultDBPath default GeoIP2 database path.
const DefaultDBPath = "GeoLite2-Country.mmdb"
// DefaultIPHeader default ip header name.
const DefaultIPHeader = ""
const (
// CountryHeader country header name.
CountryHeader = "X-GeoIP2-Country"
// RegionHeader region header name.
RegionHeader = "X-GeoIP2-Region"
// CityHeader city header name.
CityHeader = "X-GeoIP2-City"
// CoordinatesHeader geo coordinates header name.
CoordinatesHeader = "X-GeoIP2-Coordinates"
)
// GeoIPResult GeoIPResult.
type GeoIPResult struct {
country string
region string
city string
coordinates string
}
// LookupGeoIP2 LookupGeoIP2.
type LookupGeoIP2 func(ip net.IP) (*GeoIPResult, error)
// CreateCityDBLookup CreateCityDBLookup.
func CreateCityDBLookup(rdr *geoip2.CityReader) LookupGeoIP2 {
return func(ip net.IP) (*GeoIPResult, error) {
rec, err := rdr.Lookup(ip)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
retval := GeoIPResult{
country: rec.Country.ISOCode,
region: Unknown,
city: Unknown,
coordinates: Unknown,
}
if city, ok := rec.City.Names["en"]; ok {
retval.city = city
}
if rec.Subdivisions != nil {
retval.region = rec.Subdivisions[0].ISOCode
}
if rec.Location.Latitude != 0 && rec.Location.Longitude != 0 {
retval.coordinates = strconv.FormatFloat(
rec.Location.Latitude, 'f', -1, 64) + ", " + strconv.FormatFloat(
rec.Location.Longitude, 'f', -1, 64)
}
return &retval, nil
}
}
// CreateCountryDBLookup CreateCountryDBLookup.
func CreateCountryDBLookup(rdr *geoip2.CountryReader) LookupGeoIP2 {
return func(ip net.IP) (*GeoIPResult, error) {
rec, err := rdr.Lookup(ip)
if err != nil {
return nil, fmt.Errorf("%w", err)
}
retval := GeoIPResult{
country: rec.Country.ISOCode,
region: Unknown,
city: Unknown,
coordinates: Unknown,
}
return &retval, nil
}
}