Skip to content

Instantly share code, notes, and snippets.

@andrebq
Created March 23, 2015 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrebq/189ced0728cb26018e5b to your computer and use it in GitHub Desktop.
Save andrebq/189ced0728cb26018e5b to your computer and use it in GitHub Desktop.
Go bounded network listener.
package main
import (
"fmt"
"log"
"net"
"net/http"
"time"
)
func NewBoundListener(maxActive int, l net.Listener) net.Listener {
return &boundListener{l, make(chan bool, maxActive)}
}
type boundListener struct {
net.Listener
active chan bool
}
type boundConn struct {
net.Conn
active chan bool
}
func (l *boundListener) Accept() (net.Conn, error) {
l.active <- true
c, err := l.Listener.Accept()
if err != nil {
<-l.active
}
return &boundConn{c, l.active}, err
}
func (l *boundConn) Close() error {
err := l.Conn.Close()
<-l.active
return err
}
func main() {
l, err := net.Listen("tcp", "127.0.0.1:8080")
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("Sleeping...")
before := time.Now()
time.Sleep(5 * time.Second)
log.Printf("Waking up!")
fmt.Fprintf(w, "Slept for %d seconds.", time.Now().Sub(before)/time.Second)
})
http.Serve(NewBoundListener(2, l), http.DefaultServeMux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment