In Go, rate limiting can be implemented using a variety of techniques. One common method is to use the `golang.org/x/time/rate` package, which provides a simple way to control how frequently a handler can be accessed. Below is an example demonstrating how to apply rate limiting to an HTTP handler in Go.
Go, rate limiting, HTTP handler, golang, rate limiter, middleware, API
This example demonstrates how to implement rate limiting in Go applications by applying a rate limiter to HTTP handlers, ensuring that requests are not allowed to exceed a specified rate.
package main
import (
"fmt"
"net/http"
"time"
"golang.org/x/time/rate"
)
// Create a rate limiter that allows 1 request every second
var limiter = rate.NewLimiter(1, 3)
func main() {
http.HandleFunc("/", rateLimitMiddleware(helloHandler))
http.ListenAndServe(":8080", nil)
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, world!")
}
// rateLimitMiddleware limits the rate of requests
func rateLimitMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Allow access to the handler if the rate limiter permits
if limiter.Allow() {
next(w, r)
} else {
http.Error(w, "Too many requests", http.StatusTooManyRequests)
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?