gobyexample/ratelimiting/ratelimiting.go

56 lines
873 B
Go
Raw Normal View History

2024-04-29 15:09:37 +00:00
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()
}