parse.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package nat
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. // PartParser parses and validates the specified string (data) using the specified template
  8. // e.g. ip:public:private -> 192.168.0.1:80:8000
  9. func PartParser(template, data string) (map[string]string, error) {
  10. // ip:public:private
  11. var (
  12. templateParts = strings.Split(template, ":")
  13. parts = strings.Split(data, ":")
  14. out = make(map[string]string, len(templateParts))
  15. )
  16. if len(parts) != len(templateParts) {
  17. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  18. }
  19. for i, t := range templateParts {
  20. value := ""
  21. if len(parts) > i {
  22. value = parts[i]
  23. }
  24. out[t] = value
  25. }
  26. return out, nil
  27. }
  28. // ParsePortRange parses and validates the specified string as a port-range (8000-9000)
  29. func ParsePortRange(ports string) (uint64, uint64, error) {
  30. if ports == "" {
  31. return 0, 0, fmt.Errorf("Empty string specified for ports.")
  32. }
  33. if !strings.Contains(ports, "-") {
  34. start, err := strconv.ParseUint(ports, 10, 16)
  35. end := start
  36. return start, end, err
  37. }
  38. parts := strings.Split(ports, "-")
  39. start, err := strconv.ParseUint(parts[0], 10, 16)
  40. if err != nil {
  41. return 0, 0, err
  42. }
  43. end, err := strconv.ParseUint(parts[1], 10, 16)
  44. if err != nil {
  45. return 0, 0, err
  46. }
  47. if end < start {
  48. return 0, 0, fmt.Errorf("Invalid range specified for the Port: %s", ports)
  49. }
  50. return start, end, nil
  51. }