...
1 package ratelimit
2
3 import (
4 "context"
5 "errors"
6
7 "github.com/go-kit/kit/endpoint"
8 )
9
10
11
12 var ErrLimited = errors.New("rate limit exceeded")
13
14
15
16
17 type Allower interface {
18 Allow() bool
19 }
20
21
22
23
24 func NewErroringLimiter(limit Allower) endpoint.Middleware {
25 return func(next endpoint.Endpoint) endpoint.Endpoint {
26 return func(ctx context.Context, request interface{}) (interface{}, error) {
27 if !limit.Allow() {
28 return nil, ErrLimited
29 }
30 return next(ctx, request)
31 }
32 }
33 }
34
35
36
37
38 type Waiter interface {
39 Wait(ctx context.Context) error
40 }
41
42
43
44
45 func NewDelayingLimiter(limit Waiter) endpoint.Middleware {
46 return func(next endpoint.Endpoint) endpoint.Endpoint {
47 return func(ctx context.Context, request interface{}) (interface{}, error) {
48 if err := limit.Wait(ctx); err != nil {
49 return nil, err
50 }
51 return next(ctx, request)
52 }
53 }
54 }
55
56
57
58 type AllowerFunc func() bool
59
60
61 func (f AllowerFunc) Allow() bool {
62 return f()
63 }
64
65
66
67 type WaiterFunc func(ctx context.Context) error
68
69
70 func (f WaiterFunc) Wait(ctx context.Context) error {
71 return f(ctx)
72 }
73
View as plain text