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

报告相同问题?

悬赏问题

  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题