Quickstart: Implement rate-limiting with Tollbooth v8
masterTo use Tollbooth as middleware in a standard Go HTTP server, create a new limiter using tollbooth.NewLimiter, configure your IP lookup strategy, and wrap your handler with tollbooth.HTTPMiddleware.
Note: In version 8 and above, you must explicitly define how to pick the IP address using SetIPLookup. If an IP address cannot be found, the rate limiter will not be activated.
package main
import (
"net/http"
"github.com/didip/tollbooth/v8"
"github.com/didip/tollbooth/v8/limiter"
)
func HelloHandler(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Hello, World!"))
}
func main() {
// Create a request limiter per handler.
lmt := tollbooth.NewLimiter(1, nil)
// New in version >= 8, you must explicitly define how to pick the IP address.
lmt.SetIPLookup(limiter.IPLookup{
Name: "X-Real-IP",
IndexFromRight: 0,
})
// New in version >= 8, HTTPMiddleware is a standard router compatible alternative to the previously used LimitFuncHandler.
http.Handle("/", tollbooth.HTTPMiddleware(lmt)(http.HandlerFunc(HelloHandler)))
http.ListenAndServe(":12345", nil)
}