listen.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package netutil provides network utility functions, complementing the more
  5. // common ones in the net package.
  6. package netutil // import "golang.org/x/net/netutil"
  7. import (
  8. "net"
  9. "sync"
  10. )
  11. // LimitListener returns a Listener that accepts at most n simultaneous
  12. // connections from the provided Listener.
  13. func LimitListener(l net.Listener, n int) net.Listener {
  14. return &limitListener{l, make(chan struct{}, n)}
  15. }
  16. type limitListener struct {
  17. net.Listener
  18. sem chan struct{}
  19. }
  20. func (l *limitListener) acquire() { l.sem <- struct{}{} }
  21. func (l *limitListener) release() { <-l.sem }
  22. func (l *limitListener) Accept() (net.Conn, error) {
  23. l.acquire()
  24. c, err := l.Listener.Accept()
  25. if err != nil {
  26. l.release()
  27. return nil, err
  28. }
  29. return &limitListenerConn{Conn: c, release: l.release}, nil
  30. }
  31. type limitListenerConn struct {
  32. net.Conn
  33. releaseOnce sync.Once
  34. release func()
  35. }
  36. func (l *limitListenerConn) Close() error {
  37. err := l.Conn.Close()
  38. l.releaseOnce.Do(l.release)
  39. return err
  40. }