Last active
May 12, 2023 09:10
-
-
Save huantt/70097081128cdc54323e20926b522645 to your computer and use it in GitHub Desktop.
Limit requests per second in Golang using time.Tick
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 ( | |
"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