ipaddressport.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. "fmt"
  18. "net"
  19. "strconv"
  20. "strings"
  21. )
  22. // IPAddressPort implements the flag.Value interface. The argument
  23. // is validated as "ip:port".
  24. type IPAddressPort struct {
  25. IP string
  26. Port int
  27. }
  28. func (a *IPAddressPort) Set(arg string) error {
  29. arg = strings.TrimSpace(arg)
  30. parts := strings.SplitN(arg, ":", 2)
  31. if len(parts) != 2 {
  32. return errors.New("bad format in address specification")
  33. }
  34. if net.ParseIP(parts[0]) == nil {
  35. return errors.New("bad IP in address specification")
  36. }
  37. port, err := strconv.Atoi(parts[1])
  38. if err != nil {
  39. return errors.New("bad port in address specification")
  40. }
  41. a.IP = parts[0]
  42. a.Port = port
  43. return nil
  44. }
  45. func (a *IPAddressPort) String() string {
  46. return fmt.Sprintf("%s:%d", a.IP, a.Port)
  47. }