1
0

geoloader.go 1.4 KB

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