How to Implement Rate Limiting in a Go HTTP Server

Web
Implement rate limiting in a Go HTTP server using the golang.org/x/time/rate package to restrict request frequency.

Use the golang.org/x/time/rate package to implement token bucket rate limiting in your Go HTTP server.

package main

import (
	"net/http"
	"time"

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

func main() {
	limiter := rate.NewLimiter(rate.Every(time.Second), 10)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if !limiter.Allow() {
			http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
			return
		}
		w.Write([]byte("Hello, World!"))
	})

	http.ListenAndServe(":8080", nil)
}

Run go get golang.org/x/time/rate to install the dependency before building.