What Is Rate Limiting?

Go provides first-class support for rate-limiting applications in theratepackage that provides a rate limiter and interoperates with thetimepackage.

Theratepackage is part of the Go project, but the package is not available in the standard library.

Gopher the Go mascot

Youll need to drop in the package with thegetcommand.

Run this command in the terminal of your working directory to add the package to your projects dependencies.

Import these packages into your Go file for this tutorial.

overview of the rate package

Thejsonpackage is for encoding a struct as JSON to the client.

Heres the struct model with string fields youll encode to the client.

TheendpointExamplehandler function takes in anhttppackagewriterandrequestmethod instance and returns a message to the client with thewriterinstance.

Result from the rate limiting program

Youll always need to create a limiter before the authorization process.

TheAllowmethod of the limiter instance returns a boolean based on the status of authorized requests.

Themainfunction mounts the/homeendpoint to therateLimiterMiddlewarehandler function that takes in theendpointExamplehandler function.

TheListenAndServemethod starts a server on localhost port8080and returns possible errors.

The code hits the/homeendpoint ten times with a request.

Here are the result of the requests.

Similar to Go’sratepackage, npm provides theexpress-rate-limitpackage to rate-limit express applications.