sockets.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Package sockets provides helper functions to create and configure Unix or TCP sockets.
  2. package sockets
  3. import (
  4. "errors"
  5. "net"
  6. "net/http"
  7. "time"
  8. )
  9. const defaultTimeout = 10 * time.Second
  10. // ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system.
  11. var ErrProtocolNotAvailable = errors.New("protocol not available")
  12. // ConfigureTransport configures the specified [http.Transport] according to the specified proto
  13. // and addr.
  14. //
  15. // If the proto is unix (using a unix socket to communicate) or npipe the compression is disabled.
  16. // For other protos, compression is enabled. If you want to manually enable/disable compression,
  17. // make sure you do it _after_ any subsequent calls to ConfigureTransport is made against the same
  18. // [http.Transport].
  19. func ConfigureTransport(tr *http.Transport, proto, addr string) error {
  20. switch proto {
  21. case "unix":
  22. return configureUnixTransport(tr, proto, addr)
  23. case "npipe":
  24. return configureNpipeTransport(tr, proto, addr)
  25. default:
  26. tr.Proxy = http.ProxyFromEnvironment
  27. tr.DisableCompression = false
  28. tr.DialContext = (&net.Dialer{
  29. Timeout: defaultTimeout,
  30. }).DialContext
  31. }
  32. return nil
  33. }