BunRouter Middleware (BMW)
This library provides a set of useful middlewares for the BunRouter package in Go.
Installation
To install the library, run the following command:
go get github.com/atridadl/bmw
Usage
Here's an example of how to use the middlewares in this library:
package main
import (
"github.com/atridadl/bmw"
"github.com/uptrace/bunrouter"
)
func main() {
router := bunrouter.New()
router.Use(bmw.NewRateLimiter(50).RateLimit)
router.Use(bmw.RequestID())
router.Use(bmw.Secure())
// ...
}
Middlewares
RateLimit
The RateLimit middleware helps to limit the rate of incoming requests. This is useful in scenarios where you want to prevent abuse or denial-of-service attacks. Here's an example of how to use it:
router := bunrouter.New()
router.Use(bmw.NewRateLimiter(50).RateLimit) // Limit to 50 requests per minute per IP
RequestID
The RequestID middleware assigns a unique ID to each incoming request. This is useful for tracing requests in your logs or in a distributed tracing system. Here's an example of how to use it:
router := bunrouter.New()
router.Use(bmw.RequestID()) // Assign a unique ID to each request
You can retrieve the request ID in your handlers like this:
func handler(w http.ResponseWriter, req bunrouter.Request) error {
reqID := bmw.GetRequestID(req.Context())
// Now you can use reqID in your logs, etc.
// ...
}
Secure
The Secure middleware adds security-related headers to responses. This is useful for mitigating certain types of web attacks. Here's an example of how to use it:
router := bunrouter.New()
router.Use(bmw.Secure()) // Add security-related headers to responses