ipaddressport.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package flags
  15. import (
  16. "errors"
  17. "net"
  18. "strconv"
  19. "strings"
  20. )
  21. // IPAddressPort implements the flag.Value interface. The argument
  22. // is validated as "ip:port".
  23. type IPAddressPort struct {
  24. IP string
  25. Port int
  26. }
  27. func (a *IPAddressPort) Set(arg string) error {
  28. arg = strings.TrimSpace(arg)
  29. host, portStr, err := net.SplitHostPort(arg)
  30. if err != nil {
  31. return err
  32. }
  33. if net.ParseIP(host) == nil {
  34. return errors.New("bad IP in address specification")
  35. }
  36. port, err := strconv.Atoi(portStr)
  37. if err != nil {
  38. return errors.New("bad port in address specification")
  39. }
  40. a.IP = host
  41. a.Port = port
  42. return nil
  43. }
  44. func (a *IPAddressPort) String() string {
  45. return net.JoinHostPort(a.IP, strconv.Itoa(a.Port))
  46. }