geo.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package geo
  2. import (
  3. "math"
  4. "net"
  5. "github.com/golang/geo/s2"
  6. )
  7. // Provider is the interface for geoip providers
  8. type Provider interface {
  9. HasCountry() (bool, error)
  10. GetCountry(ip net.IP) (country, continent string, netmask int)
  11. HasASN() (bool, error)
  12. GetASN(net.IP) (asn string, netmask int, err error)
  13. HasLocation() (bool, error)
  14. GetLocation(ip net.IP) (location *Location, err error)
  15. }
  16. // MaxDistance is the distance returned if Distance() is
  17. // called with a nil location
  18. const MaxDistance = 360
  19. // Location is the struct the GeoIP provider packages use to
  20. // return location details for an IP.
  21. type Location struct {
  22. Country string
  23. Continent string
  24. RegionGroup string
  25. Region string
  26. Latitude float64
  27. Longitude float64
  28. Netmask int
  29. }
  30. // MaxDistance() returns the MaxDistance constant
  31. func (l *Location) MaxDistance() float64 {
  32. return MaxDistance
  33. }
  34. // Distance returns the distance between the two locations
  35. func (l *Location) Distance(to *Location) float64 {
  36. if to == nil {
  37. return MaxDistance
  38. }
  39. ll1 := s2.LatLngFromDegrees(l.Latitude, l.Longitude)
  40. ll2 := s2.LatLngFromDegrees(to.Latitude, to.Longitude)
  41. angle := ll1.Distance(ll2)
  42. return math.Abs(angle.Degrees())
  43. }