File: rate_limiter.go

package info (click to toggle)
gitlab-agent 16.11.5-1
  • links: PTS, VCS
  • area: contrib
  • in suites: experimental
  • size: 7,072 kB
  • sloc: makefile: 193; sh: 55; ruby: 3
file content (31 lines) | stat: -rw-r--r-- 806 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package httpz

import (
	"context"
	"net/http"
)

var (
	_ http.RoundTripper = &RateLimitingRoundTripper{}
)

// Limiter defines the interface to perform client-side request rate limiting.
// You can use golang.org/x/time/rate.Limiter as an implementation of this interface.
type Limiter interface {
	// Wait blocks until limiter permits an event to happen.
	// It returns an error if the Context is
	// canceled, or the expected wait time exceeds the Context's Deadline.
	Wait(context.Context) error
}

type RateLimitingRoundTripper struct {
	Delegate http.RoundTripper
	Limiter  Limiter
}

func (r *RateLimitingRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
	if err := r.Limiter.Wait(request.Context()); err != nil {
		return nil, err
	}
	return r.Delegate.RoundTrip(request)
}