limit.go 529 B

1234567891011121314151617181920212223
  1. package user
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/go-kit/kit/endpoint"
  6. "golang.org/x/time/rate"
  7. )
  8. var ErrLimitExceed = errors.New("Rate limit exceed!")
  9. // 使用x/time/rate创建限流中间件
  10. func NewTokenBucketLimitterWithBuildIn(bkt *rate.Limiter) endpoint.Middleware {
  11. return func(next endpoint.Endpoint) endpoint.Endpoint {
  12. return func(ctx context.Context, request interface{}) (response interface{}, err error) {
  13. if !bkt.Allow() {
  14. return nil, ErrLimitExceed
  15. }
  16. return next(ctx, request)
  17. }
  18. }
  19. }