I have an application which I need to restrict to a handful of IPs. I can write a middleware and return if request IP is not from allowed list, however I would like this process to be as efficient as possible. I.e. I would like to drop the connection as early as possible. What is the earliest stage I can drop connection, preferably with an HTTP response. I do not have control on host firewall or border firewall to filter traffic, and again, I won't be able to provide an HTTP response, even if I had control of firewall.
Also I would prefer if I could get a description of a life cycle of an HTTP request in gin.
Add a middleware as Lansana described.
It's important that you declare it as early in the chain as possible.
r := gin.New()
whitelist := make(map[string]bool)
whitelist["127.0.0.1"] = true
r.Use(middleware.IPWhiteList(whitelist))
I'd write the middleware like this, if you're not in the whitelist, return an error that is appropriate, in the following snippet i'm returning a JSON error.
package middleware
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func IPWhiteList(whitelist map[string]bool) gin.HandlerFunc {
return func(c *gin.Context) {
if !whitelist[c.ClientIP()] {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"status": http.StatusForbidden,
"message": "Permission denied",
})
return
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With