~juju-qa/juju-core/1.16-packaging

« back to all changes in this revision

Viewing changes to src/code.google.com/p/go.net/netutil/listen.go

  • Committer: Package Import Robot
  • Author(s): James Page
  • Date: 2013-10-10 18:07:45 UTC
  • mfrom: (1.1.10)
  • Revision ID: package-import@ubuntu.com-20131010180745-wuo0vv7hq7faavdk
Tags: 1.16.0-0ubuntu1
New upstream stable release (LP: #1219879).

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
 
5
 
// Package netutil provides network utility functions, complementing the more
6
 
// common ones in the net package.
7
 
package netutil
8
 
 
9
 
import (
10
 
        "net"
11
 
        "sync"
12
 
)
13
 
 
14
 
// LimitListener returns a Listener that accepts at most n simultaneous
15
 
// connections from the provided Listener.
16
 
func LimitListener(l net.Listener, n int) net.Listener {
17
 
        ch := make(chan struct{}, n)
18
 
        for i := 0; i < n; i++ {
19
 
                ch <- struct{}{}
20
 
        }
21
 
        return &limitListener{l, ch}
22
 
}
23
 
 
24
 
type limitListener struct {
25
 
        net.Listener
26
 
        ch chan struct{}
27
 
}
28
 
 
29
 
func (l *limitListener) Accept() (net.Conn, error) {
30
 
        <-l.ch
31
 
        c, err := l.Listener.Accept()
32
 
        if err != nil {
33
 
                return nil, err
34
 
        }
35
 
        return &limitListenerConn{Conn: c, ch: l.ch}, nil
36
 
}
37
 
 
38
 
type limitListenerConn struct {
39
 
        net.Conn
40
 
        ch    chan<- struct{}
41
 
        close sync.Once
42
 
}
43
 
 
44
 
func (l *limitListenerConn) Close() error {
45
 
        err := l.Conn.Close()
46
 
        l.close.Do(func() {
47
 
                l.ch <- struct{}{}
48
 
        })
49
 
        return err
50
 
}