Add rate limiting

This commit is contained in:
Sangeeth Sudheer 2024-04-29 20:39:37 +05:30
parent fd31a65843
commit b72ebaf843
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 59 additions and 2 deletions

View File

@ -13,7 +13,8 @@ package main
// import "git.sangeeth.dev/gobyexample/timers" // import "git.sangeeth.dev/gobyexample/timers"
// import "git.sangeeth.dev/gobyexample/tickers" // import "git.sangeeth.dev/gobyexample/tickers"
// import "git.sangeeth.dev/gobyexample/workerpools" // import "git.sangeeth.dev/gobyexample/workerpools"
import "git.sangeeth.dev/gobyexample/waitgroups" // import "git.sangeeth.dev/gobyexample/waitgroups"
import "git.sangeeth.dev/gobyexample/ratelimiting"
func main() { func main() {
// runes.Runes() // runes.Runes()
@ -29,5 +30,6 @@ func main() {
// timers.Timers() // timers.Timers()
// tickers.Tickers() // tickers.Tickers()
// workerpools.WorkerPools() // workerpools.WorkerPools()
waitgroups.WaitGroups() // waitgroups.WaitGroups()
ratelimiting.RateLimiting()
} }

View File

@ -0,0 +1,55 @@
package ratelimiting
import (
"fmt"
"time"
)
func basicRateLimiting() {
reqs := make(chan int, 5)
limiter := time.Tick(200 * time.Millisecond)
for i := range 5 {
reqs <- i
}
close(reqs)
for i := range reqs {
<-limiter
fmt.Printf("request %d at %v\n", i, time.Now())
}
}
func burstyRateLimiting() {
burstyLimiter := make(chan time.Time, 3)
// Fill burstyLimiter to brim first
for range 3 {
burstyLimiter <- time.Now()
}
go func() {
for t := range time.Tick(200 * time.Millisecond) {
burstyLimiter <- t
}
}()
reqs := make(chan int, 5)
for i := range 5 {
reqs <- i
}
close(reqs)
for i := range reqs {
t := <-burstyLimiter
fmt.Printf("request %d at %v\n", i, t)
}
}
func RateLimiting() {
fmt.Println("Demo-ing basic rate limiting")
basicRateLimiting()
fmt.Println("Demo-ing bursty rate limiting")
burstyRateLimiting()
}