1
0

geoloader.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package geodb
  2. import (
  3. "bytes"
  4. "encoding/csv"
  5. "io"
  6. "net"
  7. )
  8. func (s *Store) search(ip string) string {
  9. //See if there are cached country code for this ip
  10. ccc, ok := s.geoipCache.Load(ip)
  11. if ok {
  12. return ccc.(string)
  13. }
  14. for _, entry := range s.geodb {
  15. startIp := entry[0]
  16. endIp := entry[1]
  17. cc := entry[2]
  18. if isIPInRange(ip, startIp, endIp) {
  19. //Store results in cache
  20. s.geoipCache.Store(ip, cc)
  21. return cc
  22. }
  23. }
  24. //Not found
  25. return ""
  26. }
  27. //Parse the embedded csv as ipstart, ipend and country code entries
  28. func parseCSV(content []byte) ([][]string, error) {
  29. var records [][]string
  30. r := csv.NewReader(bytes.NewReader(content))
  31. for {
  32. record, err := r.Read()
  33. if err == io.EOF {
  34. break
  35. }
  36. if err != nil {
  37. return nil, err
  38. }
  39. records = append(records, record)
  40. }
  41. return records, nil
  42. }
  43. // Check if a ip string is within the range of two others
  44. func isIPInRange(ip, start, end string) bool {
  45. ipAddr := net.ParseIP(ip)
  46. if ipAddr == nil {
  47. return false
  48. }
  49. startAddr := net.ParseIP(start)
  50. if startAddr == nil {
  51. return false
  52. }
  53. endAddr := net.ParseIP(end)
  54. if endAddr == nil {
  55. return false
  56. }
  57. if ipAddr.To4() == nil || startAddr.To4() == nil || endAddr.To4() == nil {
  58. return false
  59. }
  60. return bytes.Compare(ipAddr.To4(), startAddr.To4()) >= 0 && bytes.Compare(ipAddr.To4(), endAddr.To4()) <= 0
  61. }