geoloader.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. for _, entry := range s.geodb {
  22. startIp := entry[0]
  23. endIp := entry[1]
  24. cc := entry[2]
  25. if isIPInRange(ip, startIp, endIp) {
  26. //Store results in cache
  27. s.geoipCache.Store(ip, cc)
  28. return cc
  29. }
  30. }
  31. //Not found
  32. return ""
  33. }
  34. //Parse the embedded csv as ipstart, ipend and country code entries
  35. func parseCSV(content []byte) ([][]string, error) {
  36. var records [][]string
  37. r := csv.NewReader(bytes.NewReader(content))
  38. for {
  39. record, err := r.Read()
  40. if err == io.EOF {
  41. break
  42. }
  43. if err != nil {
  44. return nil, err
  45. }
  46. records = append(records, record)
  47. }
  48. return records, nil
  49. }
  50. // Check if a ip string is within the range of two others
  51. func isIPInRange(ip, start, end string) bool {
  52. ipAddr := net.ParseIP(ip)
  53. if ipAddr == nil {
  54. return false
  55. }
  56. startAddr := net.ParseIP(start)
  57. if startAddr == nil {
  58. return false
  59. }
  60. endAddr := net.ParseIP(end)
  61. if endAddr == nil {
  62. return false
  63. }
  64. if ipAddr.To4() == nil || startAddr.To4() == nil || endAddr.To4() == nil {
  65. return false
  66. }
  67. return bytes.Compare(ipAddr.To4(), startAddr.To4()) >= 0 && bytes.Compare(ipAddr.To4(), endAddr.To4()) <= 0
  68. }