ip.go 934 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package opts
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. // IPOpt holds an IP. It is used to store values from CLI flags.
  7. type IPOpt struct {
  8. *net.IP
  9. }
  10. // NewIPOpt creates a new IPOpt from a reference net.IP and a
  11. // string representation of an IP. If the string is not a valid
  12. // IP it will fallback to the specified reference.
  13. func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt {
  14. o := &IPOpt{
  15. IP: ref,
  16. }
  17. o.Set(defaultVal)
  18. return o
  19. }
  20. // Set sets an IPv4 or IPv6 address from a given string. If the given
  21. // string is not parseable as an IP address it returns an error.
  22. func (o *IPOpt) Set(val string) error {
  23. ip := net.ParseIP(val)
  24. if ip == nil {
  25. return fmt.Errorf("%s is not an ip address", val)
  26. }
  27. *o.IP = ip
  28. return nil
  29. }
  30. // String returns the IP address stored in the IPOpt. If stored IP is a
  31. // nil pointer, it returns an empty string.
  32. func (o *IPOpt) String() string {
  33. if *o.IP == nil {
  34. return ""
  35. }
  36. return o.IP.String()
  37. }