reuseport.go 1.3 KB

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