handler_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package geoip
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "reflect"
  6. "strings"
  7. "testing"
  8. "github.com/mholt/caddy/caddyhttp/httpserver"
  9. maxminddb "github.com/oschwald/maxminddb-golang"
  10. )
  11. func TestToResolveGeoip(t *testing.T) {
  12. dbhandler, err := maxminddb.Open("./test-data/GeoLite2-City.mmdb")
  13. if err != nil {
  14. t.Errorf("geoip: Can't open database: GeoLite2-City.mmdb")
  15. }
  16. config := Config{}
  17. config.HeaderNameCountryCode = "X-Geoip-Country-Code"
  18. config.HeaderNameCountryIsEU = "X-Geoip-Country-Eu"
  19. config.HeaderNameCountryName = "X-Geoip-Country-Name"
  20. config.HeaderNameCityName = "X-Geoip-City-Name"
  21. config.HeaderNameLocationLat = "X-Geoip-Location-Lat"
  22. config.HeaderNameLocationLon = "X-Geoip-Location-Lon"
  23. config.HeaderNameLocationTimeZone = "X-Geoip-Location-Tz"
  24. var (
  25. gotHeaders http.Header
  26. expectedHeaders = http.Header{
  27. "X-Geoip-Country-Code": []string{"CY"},
  28. "X-Geoip-Location-Lat": []string{"34.684100"},
  29. "X-Geoip-Location-Lon": []string{"33.037900"},
  30. "X-Geoip-Location-Tz": []string{"Asia/Nicosia"},
  31. "X-Geoip-Country-Eu": []string{"false"},
  32. "X-Geoip-Country-Name": []string{"Cyprus"},
  33. "X-Geoip-City-Name": []string{"Limassol"},
  34. }
  35. )
  36. l := GeoIP{
  37. Next: httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
  38. gotHeaders = r.Header
  39. return 0, nil
  40. }),
  41. DBHandler: dbhandler,
  42. Config: config,
  43. }
  44. r := httptest.NewRequest("GET", "/", strings.NewReader(""))
  45. r.RemoteAddr = "212.50.99.193"
  46. l.ServeHTTP(httptest.NewRecorder(), r)
  47. if !reflect.DeepEqual(expectedHeaders, gotHeaders) {
  48. t.Errorf("Expected %v actual %v", expectedHeaders, gotHeaders)
  49. }
  50. }