opts/ip.go
6d59a566
 package opts
 
 import (
ca11b774
 	"fmt"
6d59a566
 	"net"
 )
 
0bd016b1
 // IPOpt holds an IP. It is used to store values from CLI flags.
6eb03c53
 type IPOpt struct {
6d59a566
 	*net.IP
 }
 
0bd016b1
 // NewIPOpt creates a new IPOpt from a reference net.IP and a
 // string representation of an IP. If the string is not a valid
 // IP it will fallback to the specified reference.
6eb03c53
 func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt {
 	o := &IPOpt{
6d59a566
 		IP: ref,
 	}
 	o.Set(defaultVal)
 	return o
 }
 
6eb03c53
 // Set sets an IPv4 or IPv6 address from a given string. If the given
39bcaee4
 // string is not parsable as an IP address it returns an error.
6eb03c53
 func (o *IPOpt) Set(val string) error {
ca11b774
 	ip := net.ParseIP(val)
 	if ip == nil {
a30fd7a9
 		return fmt.Errorf("%s is not an ip address", val)
ca11b774
 	}
b180de55
 	*o.IP = ip
6d59a566
 	return nil
 }
 
0bd016b1
 // String returns the IP address stored in the IPOpt. If stored IP is a
6eb03c53
 // nil pointer, it returns an empty string.
 func (o *IPOpt) String() string {
9ad89281
 	if *o.IP == nil {
 		return ""
 	}
b180de55
 	return o.IP.String()
6d59a566
 }
fb833947
 
 // Type returns the type of the option
 func (o *IPOpt) Type() string {
 	return "ip"
 }