ipaddressport.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package flags
  14. import (
  15. "errors"
  16. "fmt"
  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. parts := strings.SplitN(arg, ":", 2)
  30. if len(parts) != 2 {
  31. return errors.New("bad format in address specification")
  32. }
  33. if net.ParseIP(parts[0]) == nil {
  34. return errors.New("bad IP in address specification")
  35. }
  36. port, err := strconv.Atoi(parts[1])
  37. if err != nil {
  38. return errors.New("bad port in address specification")
  39. }
  40. a.IP = parts[0]
  41. a.Port = port
  42. return nil
  43. }
  44. func (a *IPAddressPort) String() string {
  45. return fmt.Sprintf("%s:%d", a.IP, a.Port)
  46. }