Created
February 2, 2015 17:17
-
-
Save kevin-cantwell/1c21feca0d1df6fba660 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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