1
0

geoloader.go 1.7 KB

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