geoloader.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. cc = s.geotrieIpv6.search(ip)
  26. } else {
  27. cc = s.geotrie.search(ip)
  28. }
  29. /*
  30. if cc != "" {
  31. s.geoipCache.Store(ip, cc)
  32. }
  33. */
  34. return cc
  35. }
  36. // Construct the trie data structure for quick lookup
  37. func constrctTrieTree(data [][]string) *trie {
  38. tt := newTrie()
  39. for _, entry := range data {
  40. startIp := entry[0]
  41. endIp := entry[1]
  42. cc := entry[2]
  43. tt.insert(startIp, cc)
  44. tt.insert(endIp, cc)
  45. }
  46. return tt
  47. }
  48. // Parse the embedded csv as ipstart, ipend and country code entries
  49. func parseCSV(content []byte) ([][]string, error) {
  50. var records [][]string
  51. r := csv.NewReader(bytes.NewReader(content))
  52. for {
  53. record, err := r.Read()
  54. if err == io.EOF {
  55. break
  56. }
  57. if err != nil {
  58. return nil, err
  59. }
  60. records = append(records, record)
  61. }
  62. return records, nil
  63. }