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 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型