reuseport.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //go:build !windows && !aix
  2. // Package reuseport provides TCP net.Listener with SO_REUSEPORT support.
  3. //
  4. // SO_REUSEPORT allows linear scaling server performance on multi-CPU servers.
  5. // See https://www.nginx.com/blog/socket-sharding-nginx-release-1-9-1/ for more details :)
  6. //
  7. // The package is based on https://github.com/kavu/go_reuseport .
  8. package reuseport
  9. import (
  10. "net"
  11. "strings"
  12. "github.com/valyala/tcplisten"
  13. )
  14. // Listen returns TCP listener with SO_REUSEPORT option set.
  15. //
  16. // The returned listener tries enabling the following TCP options, which usually
  17. // have positive impact on performance:
  18. //
  19. // - TCP_DEFER_ACCEPT. This option expects that the server reads from accepted
  20. // connections before writing to them.
  21. //
  22. // - TCP_FASTOPEN. See https://lwn.net/Articles/508865/ for details.
  23. //
  24. // Use https://github.com/valyala/tcplisten if you want customizing
  25. // these options.
  26. //
  27. // Only tcp4 and tcp6 networks are supported.
  28. //
  29. // ErrNoReusePort error is returned if the system doesn't support SO_REUSEPORT.
  30. func Listen(network, addr string) (net.Listener, error) {
  31. ln, err := cfg.NewListener(network, addr)
  32. if err != nil && strings.Contains(err.Error(), "SO_REUSEPORT") {
  33. return nil, &ErrNoReusePort{err}
  34. }
  35. return ln, err
  36. }
  37. var cfg = &tcplisten.Config{
  38. ReusePort: true,
  39. DeferAccept: true,
  40. FastOpen: true,
  41. }