Skip to content

Instantly share code, notes, and snippets.

@huantt
Last active May 12, 2023 09:10
Show Gist options
  • Save huantt/70097081128cdc54323e20926b522645 to your computer and use it in GitHub Desktop.
Save huantt/70097081128cdc54323e20926b522645 to your computer and use it in GitHub Desktop.
Limit requests per second in Golang using time.Tick
package main
import (
"fmt"
"time"
)
func main() {
// Rate limit to 10 requests per second
for i := 0; i < 100; i++ {
go sendRequest(i + 1)
}
// Wait for all requests to complete
time.Sleep(time.Second)
}
var limit = 10
var rate = time.Tick(time.Second / time.Duration(limit))
func sendRequest(i int) {
<-rate // Wait for the next tick
fmt.Printf("Sent request %d at %v\n", i, time.Now())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment