1
0

geoloader.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package geodb
  2. import (
  3. "bytes"
  4. "encoding/csv"
  5. "io"
  6. "strings"
  7. "imuslab.com/zoraxy/mod/netutils"
  8. )
  9. func (s *Store) search(ip string) string {
  10. if strings.Contains(ip, ",") {
  11. //This is a CF proxied request. We only need the front part
  12. //Example 219.71.102.145, 172.71.139.178
  13. ip = strings.Split(ip, ",")[0]
  14. ip = strings.TrimSpace(ip)
  15. }
  16. //See if there are cached country code for this ip
  17. /*
  18. ccc, ok := s.geoipCache.Load(ip)
  19. if ok {
  20. return ccc.(string)
  21. }
  22. */
  23. //Search in geotrie tree
  24. cc := ""
  25. if netutils.IsIPv6(ip) {
  26. if s.geotrieIpv6 == nil {
  27. cc = s.slowSearchIpv6(ip)
  28. } else {
  29. cc = s.geotrieIpv6.search(ip)
  30. }
  31. } else {
  32. if s.geotrie == nil {
  33. cc = s.slowSearchIpv4(ip)
  34. } else {
  35. cc = s.geotrie.search(ip)
  36. }
  37. }
  38. /*
  39. if cc != "" {
  40. s.geoipCache.Store(ip, cc)
  41. }
  42. */
  43. return cc
  44. }
  45. // Construct the trie data structure for quick lookup
  46. func constrctTrieTree(data [][]string) *trie {
  47. tt := newTrie()
  48. for _, entry := range data {
  49. startIp := entry[0]
  50. endIp := entry[1]
  51. cc := entry[2]
  52. tt.insert(startIp, cc)
  53. tt.insert(endIp, cc)
  54. }
  55. return tt
  56. }
  57. // Parse the embedded csv as ipstart, ipend and country code entries
  58. func parseCSV(content []byte) ([][]string, error) {
  59. var records [][]string
  60. r := csv.NewReader(bytes.NewReader(content))
  61. for {
  62. record, err := r.Read()
  63. if err == io.EOF {
  64. break
  65. }
  66. if err != nil {
  67. return nil, err
  68. }
  69. records = append(records, record)
  70. }
  71. return records, nil
  72. }