dtrz99313 2018-10-04 03:56 采纳率: 100%
浏览 1995
已采纳

在Go gin中实施IP限制

I'm setting up a small demo app I'd like only accessible from my home IP address for now, and maybe a small set of technical people I'll coordinate and share with.

I looked through the readme here, but couldn't find: https://github.com/gin-gonic/gin

---what's the canonical, minimal example for how to limit access on an app to only particular IP addresses in gin?

(Also, any reason this is a particularly unsafe idea in 2018?)

  • 写回答

1条回答 默认 最新

  • duanbei2914 2018-10-04 04:50
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?