geoip.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package main
  2. import (
  3. "github.com/abh/geodns/countries"
  4. "github.com/abh/geoip"
  5. "log"
  6. "net"
  7. "strings"
  8. "time"
  9. )
  10. type GeoIP struct {
  11. country *geoip.GeoIP
  12. hasCountry bool
  13. countryLastLoad time.Time
  14. city *geoip.GeoIP
  15. cityLastLoad time.Time
  16. hasCity bool
  17. }
  18. var geoIP = new(GeoIP)
  19. func (g *GeoIP) GetCountry(ip net.IP) (country, continent string, netmask int) {
  20. if g.country == nil {
  21. return "", "", 0
  22. }
  23. country, netmask = geoIP.country.GetCountry(ip.String())
  24. if len(country) > 0 {
  25. country = strings.ToLower(country)
  26. continent = countries.CountryContinent[country]
  27. }
  28. return
  29. }
  30. func (g *GeoIP) GetCountryRegion(ip net.IP) (country, continent, regionGroup, region string, netmask int) {
  31. if g.city == nil {
  32. log.Println("No city database available")
  33. country, continent, netmask = g.GetCountry(ip)
  34. return
  35. }
  36. record := geoIP.city.GetRecord(ip.String())
  37. country = record.CountryCode
  38. region = record.Region
  39. if len(country) > 0 {
  40. country = strings.ToLower(country)
  41. continent = countries.CountryContinent[country]
  42. if len(region) > 0 {
  43. region = country + "-" + strings.ToLower(region)
  44. regionGroup = countries.CountryRegionGroup(country, region)
  45. }
  46. }
  47. return
  48. }
  49. func (g *GeoIP) setDirectory() {
  50. if len(Config.GeoIP.Directory) > 0 {
  51. geoip.SetCustomDirectory(Config.GeoIP.Directory)
  52. }
  53. }
  54. func (g *GeoIP) setupGeoIPCountry() {
  55. if g.country != nil {
  56. return
  57. }
  58. g.setDirectory()
  59. gi, err := geoip.OpenType(geoip.GEOIP_COUNTRY_EDITION)
  60. if gi == nil || err != nil {
  61. log.Printf("Could not open country GeoIP database: %s\n", err)
  62. return
  63. }
  64. g.countryLastLoad = time.Now()
  65. g.hasCity = true
  66. g.country = gi
  67. }
  68. func (g *GeoIP) setupGeoIPCity() {
  69. if g.city != nil {
  70. return
  71. }
  72. g.setDirectory()
  73. gi, err := geoip.OpenType(geoip.GEOIP_CITY_EDITION_REV1)
  74. if gi == nil || err != nil {
  75. log.Printf("Could not open city GeoIP database: %s\n", err)
  76. return
  77. }
  78. g.countryLastLoad = time.Now()
  79. g.hasCity = true
  80. g.city = gi
  81. }