setup.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. rr, ok := w.(*httpserver.ResponseRecorder)
  75. log.Printf("%v %v", rr, ok)
  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_time_zone", record.Location.TimeZone)
  83. }
  84. func getClientIP(r *http.Request, strict bool) (net.IP, error) {
  85. var ip string
  86. // Use the client ip from the 'X-Forwarded-For' header, if available.
  87. if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" && !strict {
  88. ips := strings.Split(fwdFor, ", ")
  89. ip = ips[0]
  90. } else {
  91. // Otherwise, get the client ip from the request remote address.
  92. var err error
  93. ip, _, err = net.SplitHostPort(r.RemoteAddr)
  94. if err != nil {
  95. if serr, ok := err.(*net.AddrError); ok && serr.Err == "missing port in address" { // It's not critical try parse
  96. ip = r.RemoteAddr
  97. } else {
  98. log.Printf("Error when SplitHostPort: %v", serr.Err)
  99. return nil, err
  100. }
  101. }
  102. }
  103. // Parse the ip address string into a net.IP.
  104. parsedIP := net.ParseIP(ip)
  105. if parsedIP == nil {
  106. return nil, errors.New("unable to parse address")
  107. }
  108. return parsedIP, nil
  109. }
  110. func newReplacer(r *http.Request) httpserver.Replacer {
  111. return httpserver.NewReplacer(r, nil, "")
  112. }