Skip to content

Instantly share code, notes, and snippets.

@kevin-cantwell
Created February 2, 2015 17:17
Show Gist options
  • Save kevin-cantwell/1c21feca0d1df6fba660 to your computer and use it in GitHub Desktop.
Save kevin-cantwell/1c21feca0d1df6fba660 to your computer and use it in GitHub Desktop.
// Limits concurrent tasks to a limit of n. If limit is
// reached, return error instead of running task
type RateLimiter struct {
MaxConcurrent int
// Add whatever you need
taskChan chan struct{}
}
func (l *RateLimiter) Limit(task func()) error {
select {
case l.taskChan <- struct{}{}:
go func() {
task()
<-l.taskChan
}()
return nil
default:
return errors.New("Rate limit met")
}
}
func NewRateLimiter(limit int) *RateLimiter {
return &RateLimiter{
MaxConcurrent: limit,
taskChan: make(chan struct{}, limit),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment