setup.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. } `maxminddb:"country"`
  26. City struct {
  27. Names map[string]string `maxminddb:"names"`
  28. } `maxminddb:"city"`
  29. Location struct {
  30. Latitude float64 `maxminddb:"latitude"`
  31. Longitude float64 `maxminddb:"longitude"`
  32. TimeZone string `maxminddb:"time_zone"`
  33. } `maxminddb:"location"`
  34. }
  35. // Init initializes the plugin
  36. func init() {
  37. caddy.RegisterPlugin("geoip", caddy.Plugin{
  38. ServerType: "http",
  39. Action: setup,
  40. })
  41. }
  42. func setup(c *caddy.Controller) error {
  43. config, err := parseConfig(c)
  44. if err != nil {
  45. return err
  46. }
  47. dbhandler, err := maxminddb.Open(config.DatabasePath)
  48. if err != nil {
  49. return c.Err("geoip: Can't open database: " + config.DatabasePath)
  50. }
  51. // Create new middleware
  52. newMiddleWare := func(next httpserver.Handler) httpserver.Handler {
  53. return &GeoIP{
  54. Next: next,
  55. DBHandler: dbhandler,
  56. Config: config,
  57. }
  58. }
  59. // Add middleware
  60. cfg := httpserver.GetConfig(c)
  61. cfg.AddMiddleware(newMiddleWare)
  62. return nil
  63. }
  64. func (gip GeoIP) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
  65. gip.lookupLocation(w, r)
  66. return gip.Next.ServeHTTP(w, r)
  67. }
  68. func (gip GeoIP) lookupLocation(w http.ResponseWriter, r *http.Request) {
  69. clientIP, _ := getClientIP(r, true)
  70. replacer := newReplacer(r)
  71. var record = GeoIPRecord{}
  72. err := gip.DBHandler.Lookup(clientIP, &record)
  73. if err != nil {
  74. log.Println(err)
  75. }
  76. replacer.Set("geoip_country_code", record.Country.ISOCode)
  77. replacer.Set("geoip_country_name", record.Country.Names["en"])
  78. replacer.Set("geoip_country_eu", strconv.FormatBool(record.Country.IsInEuropeanUnion))
  79. replacer.Set("geoip_city_name", record.City.Names["en"])
  80. replacer.Set("geoip_latitude", strconv.FormatFloat(record.Location.Latitude, 'f', 6, 64))
  81. replacer.Set("geoip_longitude", strconv.FormatFloat(record.Location.Longitude, 'f', 6, 64))
  82. replacer.Set("geoip_geohash", geohash.Encode(record.Location.Latitude, record.Location.Longitude))
  83. replacer.Set("geoip_time_zone", record.Location.TimeZone)
  84. if rr, ok := w.(*httpserver.ResponseRecorder); ok {
  85. rr.Replacer = replacer
  86. }
  87. }
  88. func getClientIP(r *http.Request, strict bool) (net.IP, error) {
  89. var ip string
  90. // Use the client ip from the 'X-Forwarded-For' header, if available.
  91. if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" && !strict {
  92. ips := strings.Split(fwdFor, ", ")
  93. ip = ips[0]
  94. } else {
  95. // Otherwise, get the client ip from the request remote address.
  96. var err error
  97. ip, _, err = net.SplitHostPort(r.RemoteAddr)
  98. if err != nil {
  99. if serr, ok := err.(*net.AddrError); ok && serr.Err == "missing port in address" { // It's not critical try parse
  100. ip = r.RemoteAddr
  101. } else {
  102. log.Printf("Error when SplitHostPort: %v", serr.Err)
  103. return nil, err
  104. }
  105. }
  106. }
  107. // Parse the ip address string into a net.IP.
  108. parsedIP := net.ParseIP(ip)
  109. if parsedIP == nil {
  110. return nil, errors.New("unable to parse address")
  111. }
  112. return parsedIP, nil
  113. }
  114. func newReplacer(r *http.Request) httpserver.Replacer {
  115. return httpserver.NewReplacer(r, nil, "")
  116. }