Created
March 31, 2023 20:02
-
-
Save iyashjayesh/5e6fff62ba8f8d864d76f39ef8d2671f to your computer and use it in GitHub Desktop.
Implementing Rate Limiting in Go APIs.
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" | |
"sync" | |
"time" | |
) | |
type RateLimiter struct { | |
sync.Mutex | |
requests int | |
requestsLimit int | |
interval time.Duration | |
} | |
func NewRateLimiter(requestsLimit int, interval time.Duration) *RateLimiter { | |
return &RateLimiter{ | |
requests: 0, | |
requestsLimit: requestsLimit, | |
interval: interval, | |
} | |
} | |
func (rl *RateLimiter) AllowRequest() bool { | |
rl.Lock() | |
defer rl.Unlock() | |
if rl.requests >= rl.requestsLimit { | |
return false | |
} | |
rl.requests++ | |
time.AfterFunc(rl.interval, func() { | |
rl.Lock() | |
defer rl.Unlock() | |
rl.requests-- | |
}) | |
return true | |
} | |
func main() { | |
rl := NewRateLimiter(3, time.Second*10) | |
for i := 1; i <= 10; i++ { | |
if rl.AllowRequest() { | |
fmt.Printf("Request %d allowed.\n", i) | |
} else { | |
fmt.Printf("Request %d denied.\n", i) | |
} | |
time.Sleep(time.Second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment