addrs.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package flags
  2. import (
  3. "errors"
  4. "net"
  5. "strconv"
  6. "strings"
  7. )
  8. // Addrs implements the flag.Value interface to allow users to define multiple
  9. // listen addresses on the command-line
  10. type Addrs []string
  11. // Set parses a command line set of listen addresses, formatted like:
  12. // 127.0.0.1:7001,10.1.1.2:80
  13. func (as *Addrs) Set(s string) error {
  14. parsed := make([]string, 0)
  15. for _, in := range strings.Split(s, ",") {
  16. a := strings.TrimSpace(in)
  17. if err := validateAddr(a); err != nil {
  18. return err
  19. }
  20. parsed = append(parsed, a)
  21. }
  22. if len(parsed) == 0 {
  23. return errors.New("no valid addresses given!")
  24. }
  25. *as = parsed
  26. return nil
  27. }
  28. func (as *Addrs) String() string {
  29. return strings.Join(*as, ",")
  30. }
  31. // validateAddr ensures that the provided string is a valid address. Valid
  32. // addresses are of the form IP:port.
  33. // Returns an error if the address is invalid, else nil.
  34. func validateAddr(s string) error {
  35. parts := strings.SplitN(s, ":", 2)
  36. if len(parts) != 2 {
  37. return errors.New("bad format in address specification")
  38. }
  39. if net.ParseIP(parts[0]) == nil {
  40. return errors.New("bad IP in address specification")
  41. }
  42. if _, err := strconv.Atoi(parts[1]); err != nil {
  43. return errors.New("bad port in address specification")
  44. }
  45. return nil
  46. }