How to Build a Rate Limiter Service in Go

Web
Implement a Go rate limiter using the golang.org/x/time/rate package to control request frequency and prevent server overload.

Use the golang.org/x/time/rate package to implement a token bucket rate limiter in Go.

package main

import (
	"fmt"
	"net/http"
	"time"

	"golang.org/x/time/rate"
)

func main() {
	// Allow 2 requests per second
	limiter := rate.NewLimiter(rate.Limit(2), 1)

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if !limiter.Allow() {
			http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
			return
		}
		fmt.Fprintln(w, "Hello, client!")
	})

	fmt.Println("Server starting on :8080")
	http.ListenAndServe(":8080", mux)
}

Install the dependency first:

go get golang.org/x/time/rate