Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement public, non-struct Wrap() and WrapContext() functions #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions wrap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package ratelimit

import (
"context"
"time"
)

// Wrap wraps the passed function within another function, which no parameters
// and calls RateLimit using fn(). Helpful for building functions which are "preloaded" with
// a rate limiter, rather than calling RateLimit around every function call.
func Wrap(fn RateLimiterFn, callsPerInterval int64, interval time.Duration) WrappedFn {
r := NewRateLimiter(callsPerInterval, interval)

return func() error {
return r.RateLimit(fn)
}
}

// WrapContext wraps the passed function within another function, which takes a single context.Context parameter
// and calls RateLimitContext using fn() and that context. Helpful for building functions which are "preloaded" with
// a rate limiter, rather than calling RateLimitContext around every function call.
func WrapContext(fn RateLimiterFn, callsPerInterval int64, interval time.Duration) WrappedFnContext {
r := NewRateLimiter(callsPerInterval, interval)

return func(ctx context.Context) error {
return r.RateLimitContext(ctx, fn)
}
}