1
0

geodb.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package geodb
  2. import (
  3. _ "embed"
  4. "net/http"
  5. "imuslab.com/zoraxy/mod/database"
  6. "imuslab.com/zoraxy/mod/netutils"
  7. )
  8. //go:embed geoipv4.csv
  9. var geoipv4 []byte //Geodb dataset for ipv4
  10. //go:embed geoipv6.csv
  11. var geoipv6 []byte //Geodb dataset for ipv6
  12. type Store struct {
  13. geodb [][]string //Parsed geodb list
  14. geodbIpv6 [][]string //Parsed geodb list for ipv6
  15. geotrie *trie
  16. geotrieIpv6 *trie
  17. sysdb *database.Database
  18. option *StoreOptions
  19. }
  20. type StoreOptions struct {
  21. AllowSlowIpv4LookUp bool
  22. AllowSloeIpv6Lookup bool
  23. }
  24. type CountryInfo struct {
  25. CountryIsoCode string
  26. ContinetCode string
  27. }
  28. func NewGeoDb(sysdb *database.Database, option *StoreOptions) (*Store, error) {
  29. parsedGeoData, err := parseCSV(geoipv4)
  30. if err != nil {
  31. return nil, err
  32. }
  33. parsedGeoDataIpv6, err := parseCSV(geoipv6)
  34. if err != nil {
  35. return nil, err
  36. }
  37. var ipv4Trie *trie
  38. if !option.AllowSlowIpv4LookUp {
  39. ipv4Trie = constrctTrieTree(parsedGeoData)
  40. }
  41. var ipv6Trie *trie
  42. if !option.AllowSloeIpv6Lookup {
  43. ipv6Trie = constrctTrieTree(parsedGeoDataIpv6)
  44. }
  45. return &Store{
  46. geodb: parsedGeoData,
  47. geotrie: ipv4Trie,
  48. geodbIpv6: parsedGeoDataIpv6,
  49. geotrieIpv6: ipv6Trie,
  50. sysdb: sysdb,
  51. option: option,
  52. }, nil
  53. }
  54. func (s *Store) ResolveCountryCodeFromIP(ipstring string) (*CountryInfo, error) {
  55. cc := s.search(ipstring)
  56. return &CountryInfo{
  57. CountryIsoCode: cc,
  58. ContinetCode: "",
  59. }, nil
  60. }
  61. func (s *Store) Close() {
  62. }
  63. func (s *Store) GetRequesterCountryISOCode(r *http.Request) string {
  64. ipAddr := netutils.GetRequesterIP(r)
  65. if ipAddr == "" {
  66. return ""
  67. }
  68. if netutils.IsPrivateIP(ipAddr) {
  69. return "LAN"
  70. }
  71. countryCode, err := s.ResolveCountryCodeFromIP(ipAddr)
  72. if err != nil {
  73. return ""
  74. }
  75. return countryCode.CountryIsoCode
  76. }