reuseport.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //go:build !windows && !aix && !solaris
  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/fasthttp/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. // Only tcp4 and tcp6 networks are supported.
  25. //
  26. // ErrNoReusePort error is returned if the system doesn't support SO_REUSEPORT.
  27. func Listen(network, addr string) (net.Listener, error) {
  28. ln, err := cfg.NewListener(network, addr)
  29. if err != nil && strings.Contains(err.Error(), "SO_REUSEPORT") {
  30. return nil, &ErrNoReusePort{err: err}
  31. }
  32. return ln, err
  33. }
  34. var cfg = &tcplisten.Config{
  35. ReusePort: true,
  36. DeferAccept: true,
  37. FastOpen: true,
  38. }