Skip to content

Instantly share code, notes, and snippets.

@ernesto-jimenez
Created January 26, 2015 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ernesto-jimenez/e4e76c55a7020bd37e20 to your computer and use it in GitHub Desktop.
Save ernesto-jimenez/e4e76c55a7020bd37e20 to your computer and use it in GitHub Desktop.
Limiting the amount of requests in-flight
package main
import (
"fmt"
"net/http"
"sync"
)
type LimitedRoundTripper struct {
inflight chan interface{}
rt http.RoundTripper
}
func NewLimitedRoundTripper(n int, rt http.RoundTripper) *LimitedRoundTripper {
return &LimitedRoundTripper{
inflight: make(chan interface{}, n),
rt: rt,
}
}
func (l *LimitedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
defer func() {
<-l.inflight
}()
fmt.Println("waiting")
l.inflight <- nil
fmt.Println("requesting")
r, err := l.rt.RoundTrip(req)
fmt.Println("done")
return r, err
}
func main() {
c := http.Client{Transport: NewLimitedRoundTripper(3, http.DefaultTransport)}
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
r, _ := c.Get("http://localistico.com")
r.Body.Close()
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment