2016-10-27 14:58:10 +03:00
|
|
|
package ratelimit
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/micro/go-micro/client"
|
|
|
|
"github.com/micro/go-micro/server"
|
|
|
|
"go.uber.org/ratelimit"
|
|
|
|
|
2018-03-03 15:28:44 +03:00
|
|
|
"context"
|
2016-10-27 14:58:10 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type clientWrapper struct {
|
|
|
|
r ratelimit.Limiter
|
|
|
|
client.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *clientWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
|
|
|
c.r.Take()
|
|
|
|
return c.Client.Call(ctx, req, rsp, opts...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewClientWrapper creates a blocking side rate limiter
|
2019-03-14 15:19:22 +03:00
|
|
|
func NewClientWrapper(rate int, opts ...ratelimit.Option) client.Wrapper {
|
|
|
|
r := ratelimit.New(rate, opts...)
|
2016-10-27 14:58:10 +03:00
|
|
|
|
|
|
|
return func(c client.Client) client.Client {
|
|
|
|
return &clientWrapper{r, c}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewHandlerWrapper creates a blocking server side rate limiter
|
2019-03-14 15:19:22 +03:00
|
|
|
func NewHandlerWrapper(rate int, opts ...ratelimit.Option) server.HandlerWrapper {
|
|
|
|
r := ratelimit.New(rate, opts...)
|
2016-10-27 14:58:10 +03:00
|
|
|
|
|
|
|
return func(h server.HandlerFunc) server.HandlerFunc {
|
|
|
|
return func(ctx context.Context, req server.Request, rsp interface{}) error {
|
|
|
|
r.Take()
|
|
|
|
return h(ctx, req, rsp)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|