github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/os/net.go (about)

     1  package os
     2  
     3  import (
     4  	"net"
     5  	"strings"
     6  )
     7  
     8  // Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol,
     9  // eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock"
    10  func Connect(protoAddr string) (net.Conn, error) {
    11  	proto, address := ProtocolAndAddress(protoAddr)
    12  	conn, err := net.Dial(proto, address)
    13  	return conn, err
    14  }
    15  
    16  // ProtocolAndAddress splits an address into the protocol and address components.
    17  // For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080".
    18  // If the address has no protocol prefix, the default is "tcp".
    19  func ProtocolAndAddress(listenAddr string) (string, string) {
    20  	protocol, address := "tcp", listenAddr
    21  	parts := strings.SplitN(address, "://", 2)
    22  	if len(parts) == 2 {
    23  		protocol, address = parts[0], parts[1]
    24  	}
    25  	return protocol, address
    26  }