github.com/haraldrudell/parl@v0.4.176/iana/internet-socket.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package iana
     7  
     8  import (
     9  	"net/netip"
    10  
    11  	"github.com/haraldrudell/parl/perrors"
    12  )
    13  
    14  // InternetSocket is a unique named type for socket identifiers based on protocol, IP address and possibly port number.
    15  //   - InternetSocket is fmt.Stringer
    16  //   - InternetSocket is ordered
    17  type InternetSocket string
    18  
    19  // NewInternetSocket returns an InternetSocket socket identifier based on protocol, IP address and port
    20  func NewInternetSocket(protocol Protocol, addrPort netip.AddrPort) (internetSocket InternetSocket, err error) {
    21  	if !protocol.IsValid() {
    22  		err = perrors.NewPF("protocol not valid")
    23  		return
    24  	}
    25  	if !addrPort.IsValid() {
    26  		err = perrors.NewPF("addrPort not valid")
    27  		return
    28  	}
    29  
    30  	// remove possible Zone
    31  	if addrPort.Addr().Zone() != "" {
    32  		addrPort = netip.AddrPortFrom(addrPort.Addr().WithZone(""), addrPort.Port())
    33  	}
    34  
    35  	if addrPort.Port() == 0 {
    36  		internetSocket, err = NewInternetSocketNoPort(protocol, addrPort.Addr())
    37  		return
    38  	}
    39  
    40  	internetSocket = InternetSocket(protocol.String() + addrPort.String())
    41  
    42  	return
    43  }
    44  
    45  // NewInternetSocket1 returns an InternetSocket socket identifier based on protocol, IP address and port, panics on error
    46  func NewInternetSocket1(protocol Protocol, addrPort netip.AddrPort) (internetSocket InternetSocket) {
    47  	var err error
    48  	internetSocket, err = NewInternetSocket(protocol, addrPort)
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  	return
    53  }
    54  
    55  // NewInternetSocketNoPort returns an InternetSocket socket identifier based on protocol and IP address
    56  func NewInternetSocketNoPort(protocol Protocol, addr netip.Addr) (internetSocket InternetSocket, err error) {
    57  	if !protocol.IsValid() {
    58  		err = perrors.NewPF("protocol not valid")
    59  		return
    60  	}
    61  	if !addr.IsValid() {
    62  		err = perrors.NewPF("Addr not valid")
    63  		return
    64  	}
    65  	internetSocket = InternetSocket(protocol.String() + addr.String())
    66  	return
    67  }
    68  
    69  func (is InternetSocket) IsZeroValue() (isZeroValue bool) {
    70  	return is == ""
    71  }
    72  
    73  func (is InternetSocket) String() (s string) {
    74  	return string(is)
    75  }