ipaddressport.go 770 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package flags
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "strings"
  8. )
  9. // IPAddressPort implements the flag.Value interface. The argument
  10. // is validated as "ip:port".
  11. type IPAddressPort struct {
  12. IP string
  13. Port int
  14. }
  15. func (a *IPAddressPort) Set(arg string) error {
  16. arg = strings.TrimSpace(arg)
  17. parts := strings.SplitN(arg, ":", 2)
  18. if len(parts) != 2 {
  19. return errors.New("bad format in address specification")
  20. }
  21. if net.ParseIP(parts[0]) == nil {
  22. return errors.New("bad IP in address specification")
  23. }
  24. port, err := strconv.Atoi(parts[1])
  25. if err != nil {
  26. return errors.New("bad port in address specification")
  27. }
  28. a.IP = parts[0]
  29. a.Port = port
  30. return nil
  31. }
  32. func (a *IPAddressPort) String() string {
  33. return fmt.Sprintf("%s:%d", a.IP, a.Port)
  34. }