forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratelimit.go
58 lines (48 loc) · 1.41 KB
/
ratelimit.go
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package ratelimit
import (
"time"
"github.com/juju/ratelimit"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/server"
"golang.org/x/net/context"
)
type clientWrapper struct {
fn func() error
client.Client
}
func limit(b *ratelimit.Bucket, wait bool, errId string) func() error {
return func() error {
if wait {
time.Sleep(b.Take(1))
} else if b.TakeAvailable(1) == 0 {
return errors.New(errId, "too many request", 429)
}
return nil
}
}
func (c *clientWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
if err := c.fn(); err != nil {
return err
}
return c.Client.Call(ctx, req, rsp, opts...)
}
// NewClientWrapper takes a rate limiter and wait flag and returns a client Wrapper.
func NewClientWrapper(b *ratelimit.Bucket, wait bool) client.Wrapper {
fn := limit(b, wait, "go.micro.client")
return func(c client.Client) client.Client {
return &clientWrapper{fn, c}
}
}
// NewHandlerWrapper takes a rate limiter and wait flag and returns a client Wrapper.
func NewHandlerWrapper(b *ratelimit.Bucket, wait bool) server.HandlerWrapper {
fn := limit(b, wait, "go.micro.server")
return func(h server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
if err := fn(); err != nil {
return err
}
return h(ctx, req, rsp)
}
}
}