setup.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. )
  13. // GeoIP represents a middleware instance
  14. type GeoIP struct {
  15. Next httpserver.Handler
  16. DBHandler *maxminddb.Reader
  17. Config Config
  18. }
  19. type GeoIPRecord 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. var record = GeoIPRecord{}
  71. err := gip.DBHandler.Lookup(clientIP, &record)
  72. if err != nil {
  73. log.Println(err)
  74. }
  75. replacer.Set("geoip_country_code", record.Country.ISOCode)
  76. replacer.Set("geoip_country_name", record.Country.Names["en"])
  77. replacer.Set("geoip_country_eu", strconv.FormatBool(record.Country.IsInEuropeanUnion))
  78. replacer.Set("geoip_city_name", record.City.Names["en"])
  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_time_zone", record.Location.TimeZone)
  82. if rr, ok := w.(*httpserver.ResponseRecorder); ok {
  83. rr.Replacer = replacer
  84. }
  85. }
  86. func getClientIP(r *http.Request, strict bool) (net.IP, error) {
  87. var ip string
  88. // Use the client ip from the 'X-Forwarded-For' header, if available.
  89. if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" && !strict {
  90. ips := strings.Split(fwdFor, ", ")
  91. ip = ips[0]
  92. } else {
  93. // Otherwise, get the client ip from the request remote address.
  94. var err error
  95. ip, _, err = net.SplitHostPort(r.RemoteAddr)
  96. if err != nil {
  97. if serr, ok := err.(*net.AddrError); ok && serr.Err == "missing port in address" { // It's not critical try parse
  98. ip = r.RemoteAddr
  99. } else {
  100. log.Printf("Error when SplitHostPort: %v", serr.Err)
  101. return nil, err
  102. }
  103. }
  104. }
  105. // Parse the ip address string into a net.IP.
  106. parsedIP := net.ParseIP(ip)
  107. if parsedIP == nil {
  108. return nil, errors.New("unable to parse address")
  109. }
  110. return parsedIP, nil
  111. }
  112. func newReplacer(r *http.Request) httpserver.Replacer {
  113. return httpserver.NewReplacer(r, nil, "")
  114. }