7 // RequestCounter is an http.Handler that tracks the number of
8 // requests in progress.
9 type RequestCounter interface {
12 // Current() returns the number of requests in progress.
15 // Max() returns the maximum number of concurrent requests
16 // that will be accepted.
20 type limiterHandler struct {
21 requests chan struct{}
25 // NewRequestLimiter returns a RequestCounter that delegates up to
26 // maxRequests at a time to the given handler, and responds 503 to all
27 // incoming requests beyond that limit.
28 func NewRequestLimiter(maxRequests int, handler http.Handler) RequestCounter {
29 return &limiterHandler{
30 requests: make(chan struct{}, maxRequests),
35 func (h *limiterHandler) Current() int {
36 return len(h.requests)
39 func (h *limiterHandler) Max() int {
40 return cap(h.requests)
43 func (h *limiterHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
45 case h.requests <- struct{}{}:
47 // reached max requests
48 resp.WriteHeader(http.StatusServiceUnavailable)
51 h.handler.ServeHTTP(resp, req)