geodb.go 899 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package geodb
  2. import (
  3. "net"
  4. "github.com/oschwald/geoip2-golang"
  5. "imuslab.com/arozos/ReverseProxy/mod/database"
  6. )
  7. type Store struct {
  8. geodb *geoip2.Reader
  9. sysdb *database.Database
  10. }
  11. type CountryInfo struct {
  12. CountryIsoCode string
  13. ContinetCode string
  14. }
  15. func NewGeoDb(sysdb *database.Database, dbfile string) (*Store, error) {
  16. db, err := geoip2.Open(dbfile)
  17. if err != nil {
  18. return nil, err
  19. }
  20. return &Store{
  21. geodb: db,
  22. sysdb: sysdb,
  23. }, nil
  24. }
  25. func (s *Store) ResolveCountryCodeFromIP(ipstring string) (*CountryInfo, error) {
  26. // If you are using strings that may be invalid, check that ip is not nil
  27. ip := net.ParseIP(ipstring)
  28. record, err := s.geodb.City(ip)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return &CountryInfo{
  33. record.Country.IsoCode,
  34. record.Continent.Code,
  35. }, nil
  36. }
  37. func (s *Store) Close() {
  38. s.geodb.Close()
  39. }