Skip to content

Instantly share code, notes, and snippets.

@cmelbye
Last active August 29, 2015 14:18
Show Gist options
  • Save cmelbye/366e3e45157cf81ad53d to your computer and use it in GitHub Desktop.
Save cmelbye/366e3e45157cf81ad53d to your computer and use it in GitHub Desktop.
var limitSem = make(chan int, 100) // TODO(dsymonds): Use environment variable.
func limitRelease() {
// non-blocking
select {
case <-limitSem:
default:
// This should not normally happen.
log.Print("appengine: unbalanced limitSem release!")
}
}
func limitDial(network, addr string) (net.Conn, error) {
limitSem <- 1
// Dial with a timeout in case the API host is MIA.
// The connection should normally be very fast.
conn, err := net.DialTimeout(network, addr, 500*time.Millisecond)
if err != nil {
limitRelease()
return nil, err
}
lc := &limitConn{Conn: conn}
return lc, nil
}
type limitConn struct {
relonce sync.Once
net.Conn
}
func (lc *limitConn) Close() error {
defer lc.relonce.Do(func() {
limitRelease()
})
return lc.Conn.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment