handler.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package geoip
  2. import (
  3. "errors"
  4. "log"
  5. "net"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. )
  10. func (gip GeoIP) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
  11. gip.addGeoIPHeaders(w, r)
  12. return gip.Next.ServeHTTP(w, r)
  13. }
  14. var record struct {
  15. Country struct {
  16. ISOCode string `maxminddb:"iso_code"`
  17. IsInEuropeanUnion bool `maxminddb:"is_in_european_union"`
  18. Names map[string]string `maxminddb:"names"`
  19. } `maxminddb:"country"`
  20. City struct {
  21. Names map[string]string `maxminddb:"names"`
  22. } `maxminddb:"city"`
  23. Location struct {
  24. Latitude float64 `maxminddb:"latitude"`
  25. Longitude float64 `maxminddb:"longitude"`
  26. TimeZone string `maxminddb:"time_zone"`
  27. } `maxminddb:"location"`
  28. }
  29. func (gip GeoIP) addGeoIPHeaders(w http.ResponseWriter, r *http.Request) {
  30. clientIP, _ := getClientIP(r, true)
  31. err := gip.Config.DBHandler.Lookup(clientIP, &record)
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. w.Header().Add(gip.Config.HeaderNameCountryCode, record.Country.ISOCode)
  36. w.Header().Add(gip.Config.HeaderNameCountryIsEU, strconv.FormatBool(record.Country.IsInEuropeanUnion))
  37. w.Header().Add(gip.Config.HeaderNameCountryName, record.Country.Names["en"])
  38. w.Header().Add(gip.Config.HeaderNameCityName, record.City.Names["en"])
  39. w.Header().Add(gip.Config.HeaderNameLocationLat, strconv.FormatFloat(record.Location.Latitude, 'f', 6, 64))
  40. w.Header().Add(gip.Config.HeaderNameLocationLon, strconv.FormatFloat(record.Location.Longitude, 'f', 6, 64))
  41. w.Header().Add(gip.Config.HeaderNameLocationTimeZone, record.Location.TimeZone)
  42. }
  43. func getClientIP(r *http.Request, strict bool) (net.IP, error) {
  44. var ip string
  45. // Use the client ip from the 'X-Forwarded-For' header, if available.
  46. if fwdFor := r.Header.Get("X-Forwarded-For"); fwdFor != "" && !strict {
  47. ips := strings.Split(fwdFor, ", ")
  48. ip = ips[0]
  49. } else {
  50. // Otherwise, get the client ip from the request remote address.
  51. var err error
  52. ip, _, err = net.SplitHostPort(r.RemoteAddr)
  53. if err != nil {
  54. return nil, err
  55. }
  56. }
  57. // ip = "212.50.99.193"
  58. // Parse the ip address string into a net.IP.
  59. parsedIP := net.ParseIP(ip)
  60. if parsedIP == nil {
  61. return nil, errors.New("unable to parse address")
  62. }
  63. return parsedIP, nil
  64. }