Created
March 23, 2015 18:02
-
-
Save andrebq/189ced0728cb26018e5b to your computer and use it in GitHub Desktop.
Go bounded network listener.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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