You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.2 KiB

  1. package net
  2. import (
  3. "net"
  4. "strings"
  5. )
  6. // Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol,
  7. // eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock"
  8. func Connect(protoAddr string) (net.Conn, error) {
  9. proto, address := ProtocolAndAddress(protoAddr)
  10. conn, err := net.Dial(proto, address)
  11. return conn, err
  12. }
  13. // ProtocolAndAddress splits an address into the protocol and address components.
  14. // For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080".
  15. // If the address has no protocol prefix, the default is "tcp".
  16. func ProtocolAndAddress(listenAddr string) (string, string) {
  17. protocol, address := "tcp", listenAddr
  18. parts := strings.SplitN(address, "://", 2)
  19. if len(parts) == 2 {
  20. protocol, address = parts[0], parts[1]
  21. }
  22. return protocol, address
  23. }
  24. // GetFreePort gets a free port from the operating system.
  25. // Ripped from https://github.com/phayes/freeport.
  26. // BSD-licensed.
  27. func GetFreePort() (int, error) {
  28. addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
  29. if err != nil {
  30. return 0, err
  31. }
  32. l, err := net.ListenTCP("tcp", addr)
  33. if err != nil {
  34. return 0, err
  35. }
  36. defer l.Close()
  37. return l.Addr().(*net.TCPAddr).Port, nil
  38. }