How do I apply rate limiting to handlers in Go?

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) } } }

Go rate limiting HTTP handler golang rate limiter middleware API