Before I answer your question, I would like to say that it would likely be more practical to limit access to the app using firewall rules rather than in the program itself, but I digress.
To answer your question, after looking through the gin godoc reference I found that the context struct contains a ClientIp()
method that:
implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
Therefore, if you are set on doing the IP filtering in the app, you could filter based on the value returned by that method.
Using the basic example given on the Github page:
package main
import "github.com/gin-gonic/gin"
var Whitelist []string = []string{"1.2.3.4"}
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
whitelisted := false
for _, v := range Whitelist {
if v == c.ClientIP() {
whitelisted = true
}
}
if whitelisted {
c.JSON(200, gin.H{
"message": "pong",
})
} else {
c.JSON(403, gin.H{})
}
})
r.Run() // listen and serve on 0.0.0.0:8080
}