handler.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.DBHandler.Lookup(clientIP, &record)
  32. if err != nil {
  33. log.Println(err)
  34. }
  35. r.Header.Set(gip.Config.HeaderNameCountryCode, record.Country.ISOCode)
  36. r.Header.Set(gip.Config.HeaderNameCountryIsEU, strconv.FormatBool(record.Country.IsInEuropeanUnion))
  37. r.Header.Set(gip.Config.HeaderNameCountryName, record.Country.Names["en"])
  38. r.Header.Set(gip.Config.HeaderNameCityName, record.City.Names["en"])
  39. r.Header.Set(gip.Config.HeaderNameLocationLat, strconv.FormatFloat(record.Location.Latitude, 'f', 6, 64))
  40. r.Header.Set(gip.Config.HeaderNameLocationLon, strconv.FormatFloat(record.Location.Longitude, 'f', 6, 64))
  41. r.Header.Set(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. if serr, ok := err.(*net.AddrError); ok && serr.Err == "missing port in address" { // It's not critical try parse
  55. ip = r.RemoteAddr
  56. } else {
  57. log.Printf("Error when SplitHostPort: %v", serr.Err)
  58. return nil, err
  59. }
  60. }
  61. }
  62. // Parse the ip address string into a net.IP.
  63. parsedIP := net.ParseIP(ip)
  64. if parsedIP == nil {
  65. return nil, errors.New("unable to parse address")
  66. }
  67. return parsedIP, nil
  68. }