-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlimit.go
More file actions
34 lines (30 loc) · 969 Bytes
/
limit.go
File metadata and controls
34 lines (30 loc) · 969 Bytes
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
32
33
34
package mid
import (
"context"
"net/http"
)
// Limiter is the type of an object that can be used to limit the rate of some operation.
// Calling Wait on a Limiter blocks until the operation is allowed to proceed.
//
// This interface is satisfied by the *Limiter type in golang.org/x/time/rate.
type Limiter interface {
Wait(context.Context) error
}
// LimitedTransport is an [http.RoundTripper] that limits the rate of requests it makes using a [Limiter].
// After waiting for the limiter in L, it delegates to the http.RoundTripper in T.
// If T is nil, it uses [http.DefaultTransport].
type LimitedTransport struct {
L Limiter
T http.RoundTripper
}
// RoundTrip implements the [http.RoundTripper] interface.
func (lt LimitedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if err := lt.L.Wait(req.Context()); err != nil {
return nil, err
}
next := lt.T
if next == nil {
next = http.DefaultTransport
}
return next.RoundTrip(req)
}