github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/opts/ip.go (about)

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