setup.go 3.4 KB

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