middleware

I've written some painfully simple tollbooth rate-limiting middlewares for Gin and Echo, which can be copied and pasted into your code.

For those who've exposed their Go code on the internet before, you'll be keenly aware of the choice of available rate-limiters. I've done the rounds too and, being lazy, hoped to find something that'd plug straight into Gin or Echo.

It's a pretty straighforward task as you can imagine, so I ended up rolling my own and this is the result.

To keep my API definition as simple as possible, I created a very simple tollbooth wrapper, which works as a middleware for both routers. Here's how to limit requests to 1 per second:

Echo
router := gin.Default()  
router.Use(LimitMiddleware(tollbooth.NewLimiter(1, time.Second)))  
router.GET("/get", func(c *gin.Context) {  
    c.String(http.StatusOK, "Now we know...")
})
router.Run(":1234")  
Gin
router := echo.New()  
router.Use(LimitMiddleware(tollbooth.NewLimiter(1, time.Minute)))  
router.GET("/", func(c echo.Context) (err error) {  
    c.String(http.StatusOK, "Hello, Gin Limiter!")
    return
})
router.Start(":1234")  

The end result for both is that any time a user makes more than 1 request per second, they'll receive a 429 (too many requests) response.