setup.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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/oschwald/maxminddb-golang"
  12. "github.com/mmcloughlin/geohash"
  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. clientIP, _ := getClientIP(r, true)
  72. replacer := newReplacer(r)
  73. var record = GeoIPRecord{}
  74. err := gip.DBHandler.Lookup(clientIP, &record)
  75. if err != nil {
  76. log.Println(err)
  77. }
  78. replacer.Set("geoip_country_code", record.Country.ISOCode)
  79. replacer.Set("geoip_country_name", record.Country.Names["en"])
  80. replacer.Set("geoip_country_eu", strconv.FormatBool(record.Country.IsInEuropeanUnion))
  81. replacer.Set("geoip_country_geoname_id", strconv.FormatUint(record.Country.GeoNameID, 10))
  82. replacer.Set("geoip_city_name", record.City.Names["en"])
  83. replacer.Set("geoip_city_geoname_id", strconv.FormatUint(record.City.GeoNameID, 10))
  84. replacer.Set("geoip_latitude", strconv.FormatFloat(record.Location.Latitude, 'f', 6, 64))
  85. replacer.Set("geoip_longitude", strconv.FormatFloat(record.Location.Longitude, 'f', 6, 64))
  86. replacer.Set("geoip_geohash", geohash.Encode(record.Location.Latitude, record.Location.Longitude))
  87. replacer.Set("geoip_time_zone", record.Location.TimeZone)
  88. if rr, ok := w.(*httpserver.ResponseRecorder); ok {
  89. rr.Replacer = replacer
  90. }
  91. }
  92. func getClientIP(r *http.Request, strict bool) (net.IP, error) {
  93. var ip string
  94. // Use the client ip from the 'X-Forwarded-For' header, if available.
  95. if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" && !strict {
  96. ips := strings.Split(fwdFor, ", ")
  97. ip = ips[0]
  98. } else {
  99. // Otherwise, get the client ip from the request remote address.
  100. var err error
  101. ip, _, err = net.SplitHostPort(r.RemoteAddr)
  102. if err != nil {
  103. if serr, ok := err.(*net.AddrError); ok && serr.Err == "missing port in address" { // It's not critical try parse
  104. ip = r.RemoteAddr
  105. } else {
  106. log.Printf("Error when SplitHostPort: %v", serr.Err)
  107. return nil, err
  108. }
  109. }
  110. }
  111. // Parse the ip address string into a net.IP.
  112. parsedIP := net.ParseIP(ip)
  113. if parsedIP == nil {
  114. return nil, errors.New("unable to parse address")
  115. }
  116. return parsedIP, nil
  117. }
  118. func newReplacer(r *http.Request) httpserver.Replacer {
  119. return httpserver.NewReplacer(r, nil, "")
  120. }