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

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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算