setup.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package geoip
  2. import (
  3. "errors"
  4. "log"
  5. "net"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/mholt/caddy"
  10. "github.com/mholt/caddy/caddyhttp/httpserver"
  11. "github.com/mmcloughlin/geohash"
  12. "github.com/oschwald/maxminddb-golang"
  13. )
  14. // GeoIP represents a middleware instance
  15. type GeoIP struct {
  16. Next httpserver.Handler
  17. DBHandler *maxminddb.Reader
  18. Config Config
  19. }
  20. type GeoIPRecord struct {
  21. Country struct {
  22. ISOCode string `maxminddb:"iso_code"`
  23. IsInEuropeanUnion bool `maxminddb:"is_in_european_union"`
  24. Names map[string]string `maxminddb:"names"`
  25. GeoNameID uint64 `maxminddb:"geoname_id"`
  26. } `maxminddb:"country"`
  27. City struct {
  28. Names map[string]string `maxminddb:"names"`
  29. GeoNameID uint64 `maxminddb:"geoname_id"`
  30. } `maxminddb:"city"`
  31. Location struct {
  32. Latitude float64 `maxminddb:"latitude"`
  33. Longitude float64 `maxminddb:"longitude"`
  34. TimeZone string `maxminddb:"time_zone"`
  35. } `maxminddb:"location"`
  36. }
  37. // Init initializes the plugin
  38. func init() {
  39. caddy.RegisterPlugin("geoip", caddy.Plugin{
  40. ServerType: "http",
  41. Action: setup,
  42. })
  43. }
  44. func setup(c *caddy.Controller) error {
  45. config, err := parseConfig(c)
  46. if err != nil {
  47. return err
  48. }
  49. dbhandler, err := maxminddb.Open(config.DatabasePath)
  50. if err != nil {
  51. return c.Err("geoip: Can't open database: " + config.DatabasePath)
  52. }
  53. // Create new middleware
  54. newMiddleWare := func(next httpserver.Handler) httpserver.Handler {
  55. return &GeoIP{
  56. Next: next,
  57. DBHandler: dbhandler,
  58. Config: config,
  59. }
  60. }
  61. // Add middleware
  62. cfg := httpserver.GetConfig(c)
  63. cfg.AddMiddleware(newMiddleWare)
  64. return nil
  65. }
  66. func (gip GeoIP) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
  67. gip.lookupLocation(w, r)
  68. return gip.Next.ServeHTTP(w, r)
  69. }
  70. func (gip GeoIP) lookupLocation(w http.ResponseWriter, r *http.Request) {
  71. record := gip.fetchGeoipData(r)
  72. replacer := newReplacer(r)
  73. replacer.Set("geoip_country_code", record.Country.ISOCode)
  74. replacer.Set("geoip_country_name", record.Country.Names["en"])
  75. replacer.Set("geoip_country_eu", strconv.FormatBool(record.Country.IsInEuropeanUnion))
  76. replacer.Set("geoip_country_geoname_id", strconv.FormatUint(record.Country.GeoNameID, 10))
  77. replacer.Set("geoip_city_name", record.City.Names["en"])
  78. replacer.Set("geoip_city_geoname_id", strconv.FormatUint(record.City.GeoNameID, 10))
  79. replacer.Set("geoip_latitude", strconv.FormatFloat(record.Location.Latitude, 'f', 6, 64))
  80. replacer.Set("geoip_longitude", strconv.FormatFloat(record.Location.Longitude, 'f', 6, 64))
  81. replacer.Set("geoip_geohash", geohash.Encode(record.Location.Latitude, record.Location.Longitude))
  82. replacer.Set("geoip_time_zone", record.Location.TimeZone)
  83. if rr, ok := w.(*httpserver.ResponseRecorder); ok {
  84. rr.Replacer = replacer
  85. }
  86. }
  87. func (gip GeoIP) fetchGeoipData(r *http.Request) GeoIPRecord {
  88. clientIP, _ := getClientIP(r, true)
  89. var record = GeoIPRecord{}
  90. err := gip.DBHandler.Lookup(clientIP, &record)
  91. if err != nil {
  92. log.Println(err)
  93. }
  94. if record.Country.ISOCode == "" {
  95. record.Country.Names = make(map[string]string)
  96. record.City.Names = make(map[string]string)
  97. if clientIP.IsLoopback() {
  98. record.Country.ISOCode = "**"
  99. record.Country.Names["en"] = "Loopback"
  100. record.City.Names["en"] = "Loopback"
  101. } else {
  102. record.Country.ISOCode = "!!"
  103. record.Country.Names["en"] = "No Country"
  104. record.City.Names["en"] = "No City"
  105. }
  106. }
  107. return record
  108. }
  109. func getClientIP(r *http.Request, strict bool) (net.IP, error) {
  110. var ip string
  111. // Use the client ip from the 'X-Forwarded-For' header, if available.
  112. if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" && !strict {
  113. ips := strings.Split(fwdFor, ", ")
  114. ip = ips[0]
  115. } else {
  116. // Otherwise, get the client ip from the request remote address.
  117. var err error
  118. ip, _, err = net.SplitHostPort(r.RemoteAddr)
  119. if err != nil {
  120. if serr, ok := err.(*net.AddrError); ok && serr.Err == "missing port in address" { // It's not critical try parse
  121. ip = r.RemoteAddr
  122. } else {
  123. log.Printf("Error when SplitHostPort: %v", serr.Err)
  124. return nil, err
  125. }
  126. }
  127. }
  128. // Parse the ip address string into a net.IP.
  129. parsedIP := net.ParseIP(ip)
  130. if parsedIP == nil {
  131. return nil, errors.New("unable to parse address")
  132. }
  133. return parsedIP, nil
  134. }
  135. func newReplacer(r *http.Request) httpserver.Replacer {
  136. return httpserver.NewReplacer(r, nil, "")
  137. }