Created
January 10, 2018 19:41
-
-
Save xoebus/39faf917b3996742a3913fb92c99314c to your computer and use it in GitHub Desktop.
Go Rate-limit Example
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
package main | |
import ( | |
"context" | |
"fmt" | |
"time" | |
"golang.org/x/time/rate" | |
) | |
func main() { | |
limit := rate.Every(time.Second / 5) | |
limiter := rate.NewLimiter(limit, 5) | |
ctx, cancel := context.WithTimeout(context.Background(), time.Second) | |
defer cancel() | |
for i := 0; i < 15; i++ { | |
if err := limiter.Wait(ctx); err != nil { | |
fmt.Println("ran out of time!") | |
break | |
} | |
fmt.Println(i, "work!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment