forked from aablinov/caddy-geoip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.go
160 lines (137 loc) · 4.36 KB
/
setup.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package geoip
import (
"errors"
"log"
"net"
"net/http"
"strconv"
"strings"
"github.com/caddyserver/caddy"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
"github.com/mmcloughlin/geohash"
"github.com/oschwald/maxminddb-golang"
)
// GeoIP represents a middleware instance
type GeoIP struct {
Next httpserver.Handler
DBHandler *maxminddb.Reader
Config Config
}
type GeoIPRecord struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
IsInEuropeanUnion bool `maxminddb:"is_in_european_union"`
Names map[string]string `maxminddb:"names"`
GeoNameID uint64 `maxminddb:"geoname_id"`
} `maxminddb:"country"`
City struct {
Names map[string]string `maxminddb:"names"`
GeoNameID uint64 `maxminddb:"geoname_id"`
} `maxminddb:"city"`
Location struct {
Latitude float64 `maxminddb:"latitude"`
Longitude float64 `maxminddb:"longitude"`
TimeZone string `maxminddb:"time_zone"`
} `maxminddb:"location"`
}
// Init initializes the plugin
func init() {
caddy.RegisterPlugin("geoip", caddy.Plugin{
ServerType: "http",
Action: setup,
})
}
func setup(c *caddy.Controller) error {
config, err := parseConfig(c)
if err != nil {
return err
}
dbhandler, err := maxminddb.Open(config.DatabasePath)
if err != nil {
return c.Err("geoip: Can't open database: " + config.DatabasePath)
}
// Create new middleware
newMiddleWare := func(next httpserver.Handler) httpserver.Handler {
return &GeoIP{
Next: next,
DBHandler: dbhandler,
Config: config,
}
}
// Add middleware
cfg := httpserver.GetConfig(c)
cfg.AddMiddleware(newMiddleWare)
return nil
}
func (gip GeoIP) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
gip.lookupLocation(w, r)
return gip.Next.ServeHTTP(w, r)
}
func (gip GeoIP) lookupLocation(w http.ResponseWriter, r *http.Request) {
record := gip.fetchGeoipData(r)
replacer := newReplacer(r)
replacer.Set("geoip_country_code", record.Country.ISOCode)
replacer.Set("geoip_country_name", record.Country.Names["en"])
replacer.Set("geoip_country_eu", strconv.FormatBool(record.Country.IsInEuropeanUnion))
replacer.Set("geoip_country_geoname_id", strconv.FormatUint(record.Country.GeoNameID, 10))
replacer.Set("geoip_city_name", record.City.Names["en"])
replacer.Set("geoip_city_geoname_id", strconv.FormatUint(record.City.GeoNameID, 10))
replacer.Set("geoip_latitude", strconv.FormatFloat(record.Location.Latitude, 'f', 6, 64))
replacer.Set("geoip_longitude", strconv.FormatFloat(record.Location.Longitude, 'f', 6, 64))
replacer.Set("geoip_geohash", geohash.Encode(record.Location.Latitude, record.Location.Longitude))
replacer.Set("geoip_time_zone", record.Location.TimeZone)
if rr, ok := w.(*httpserver.ResponseRecorder); ok {
rr.Replacer = replacer
}
}
func (gip GeoIP) fetchGeoipData(r *http.Request) GeoIPRecord {
clientIP, _ := getClientIP(r, true)
var record = GeoIPRecord{}
err := gip.DBHandler.Lookup(clientIP, &record)
if err != nil {
log.Println(err)
}
if record.Country.ISOCode == "" {
record.Country.Names = make(map[string]string)
record.City.Names = make(map[string]string)
if clientIP.IsLoopback() {
record.Country.ISOCode = "**"
record.Country.Names["en"] = "Loopback"
record.City.Names["en"] = "Loopback"
} else {
record.Country.ISOCode = "!!"
record.Country.Names["en"] = "No Country"
record.City.Names["en"] = "No City"
}
}
return record
}
func getClientIP(r *http.Request, strict bool) (net.IP, error) {
var ip string
// Use the client ip from the 'X-Forwarded-For' header, if available.
if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" && !strict {
ips := strings.Split(fwdFor, ", ")
ip = ips[0]
} else {
// Otherwise, get the client ip from the request remote address.
var err error
ip, _, err = net.SplitHostPort(r.RemoteAddr)
if err != nil {
if serr, ok := err.(*net.AddrError); ok && serr.Err == "missing port in address" { // It's not critical try parse
ip = r.RemoteAddr
} else {
log.Printf("Error when SplitHostPort: %v", serr.Err)
return nil, err
}
}
}
// Parse the ip address string into a net.IP.
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return nil, errors.New("unable to parse address")
}
return parsedIP, nil
}
func newReplacer(r *http.Request) httpserver.Replacer {
return httpserver.NewReplacer(r, nil, "")
}