parse.go 1.5 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. // DEPRECATED: do not use, this function may be removed in a future version
  10. func PartParser(template, data string) (map[string]string, error) {
  11. // ip:public:private
  12. var (
  13. templateParts = strings.Split(template, ":")
  14. parts = strings.Split(data, ":")
  15. out = make(map[string]string, len(templateParts))
  16. )
  17. if len(parts) != len(templateParts) {
  18. return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template)
  19. }
  20. for i, t := range templateParts {
  21. value := ""
  22. if len(parts) > i {
  23. value = parts[i]
  24. }
  25. out[t] = value
  26. }
  27. return out, nil
  28. }
  29. // ParsePortRange parses and validates the specified string as a port-range (8000-9000)
  30. func ParsePortRange(ports string) (uint64, uint64, error) {
  31. if ports == "" {
  32. return 0, 0, fmt.Errorf("Empty string specified for ports.")
  33. }
  34. if !strings.Contains(ports, "-") {
  35. start, err := strconv.ParseUint(ports, 10, 16)
  36. end := start
  37. return start, end, err
  38. }
  39. parts := strings.Split(ports, "-")
  40. start, err := strconv.ParseUint(parts[0], 10, 16)
  41. if err != nil {
  42. return 0, 0, err
  43. }
  44. end, err := strconv.ParseUint(parts[1], 10, 16)
  45. if err != nil {
  46. return 0, 0, err
  47. }
  48. if end < start {
  49. return 0, 0, fmt.Errorf("Invalid range specified for the Port: %s", ports)
  50. }
  51. return start, end, nil
  52. }