Skip to content

Instantly share code, notes, and snippets.

@xoebus
Created January 10, 2018 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xoebus/39faf917b3996742a3913fb92c99314c to your computer and use it in GitHub Desktop.
Save xoebus/39faf917b3996742a3913fb92c99314c to your computer and use it in GitHub Desktop.
Go Rate-limit Example
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