1
0

geoloader.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package geodb
  2. import (
  3. "bytes"
  4. "encoding/csv"
  5. "io"
  6. "net"
  7. "strings"
  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. ccc, ok := s.geoipCache.Load(ip)
  18. if ok {
  19. return ccc.(string)
  20. }
  21. //Search in geotrie tree
  22. cc := s.geotrie.search(ip)
  23. if cc != "" {
  24. s.geoipCache.Store(ip, cc)
  25. }
  26. //Not found
  27. return ""
  28. }
  29. // Construct the trie data structure for quick lookup
  30. func constrctTrieTree(data [][]string) *trie {
  31. tt := newTrie()
  32. for _, entry := range data {
  33. startIp := entry[0]
  34. endIp := entry[1]
  35. cc := entry[2]
  36. tt.insert(startIp, cc)
  37. tt.insert(endIp, cc)
  38. }
  39. return tt
  40. }
  41. // Parse the embedded csv as ipstart, ipend and country code entries
  42. func parseCSV(content []byte) ([][]string, error) {
  43. var records [][]string
  44. r := csv.NewReader(bytes.NewReader(content))
  45. for {
  46. record, err := r.Read()
  47. if err == io.EOF {
  48. break
  49. }
  50. if err != nil {
  51. return nil, err
  52. }
  53. records = append(records, record)
  54. }
  55. return records, nil
  56. }
  57. // Check if a ip string is within the range of two others
  58. func isIPInRange(ip, start, end string) bool {
  59. ipAddr := net.ParseIP(ip)
  60. if ipAddr == nil {
  61. return false
  62. }
  63. startAddr := net.ParseIP(start)
  64. if startAddr == nil {
  65. return false
  66. }
  67. endAddr := net.ParseIP(end)
  68. if endAddr == nil {
  69. return false
  70. }
  71. if ipAddr.To4() == nil || startAddr.To4() == nil || endAddr.To4() == nil {
  72. return false
  73. }
  74. return bytes.Compare(ipAddr.To4(), startAddr.To4()) >= 0 && bytes.Compare(ipAddr.To4(), endAddr.To4()) <= 0
  75. }