github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/docker/port.go (about)

     1  package docker
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  )
     8  
     9  type Protocol string
    10  
    11  const (
    12  	ProtocolTCP Protocol = "TCP"
    13  	ProtocolUDP Protocol = "UDP"
    14  )
    15  
    16  type Port struct {
    17  	Port          int16
    18  	ContainerPort int16
    19  	Protocol      Protocol
    20  }
    21  
    22  func ParsePortString(s string) (*Port, error) {
    23  	p := Port{}
    24  	portsAndProtocol := strings.Split(s, "/")
    25  	ports := strings.Split(portsAndProtocol[0], ":")
    26  
    27  	if len(ports) != 2 {
    28  		return nil, fmt.Errorf("port:containerPort format error")
    29  	}
    30  
    31  	port, err := strconv.ParseInt(ports[0], 10, 16)
    32  	if err != nil {
    33  		return nil, fmt.Errorf("invalid port %s", ports[0])
    34  	}
    35  	p.Port = int16(port)
    36  
    37  	containerPort, err := strconv.ParseInt(ports[1], 10, 16)
    38  	if err != nil {
    39  		return nil, fmt.Errorf("invalid container port %s", ports[1])
    40  	}
    41  
    42  	p.ContainerPort = int16(containerPort)
    43  
    44  	if len(portsAndProtocol) == 2 && strings.ToUpper(portsAndProtocol[1]) == string(ProtocolUDP) {
    45  		p.Protocol = ProtocolUDP
    46  	} else {
    47  		p.Protocol = ProtocolTCP
    48  	}
    49  
    50  	return &p, nil
    51  }
    52  
    53  func (port Port) String() string {
    54  	return fmt.Sprintf("%d:%d/%s", port.Port, port.ContainerPort, port.Protocol)
    55  }
    56  
    57  func (port Port) MarshalYAML() (interface{}, error) {
    58  	return port.String(), nil
    59  }
    60  
    61  func (port *Port) UnmarshalYAML(unmarshal func(interface{}) error) error {
    62  	var v string
    63  	err := unmarshal(&v)
    64  	if err == nil {
    65  		p, err := ParsePortString(v)
    66  		if err != nil {
    67  			return err
    68  		}
    69  		*port = *p
    70  	}
    71  	return nil
    72  }