在 Go gin 中实现 IP 限制

Implementing IP restrictions in Go gin

我正在设置一个小型演示应用程序,我希望目前只能从我的家庭 IP 地址访问,也许我会与一小部分技术人员进行协调和共享。

我在这里查看了自述文件,但找不到: https://github.com/gin-gonic/gin

---关于如何将应用程序的访问限制为仅对杜松子酒中的特定 IP 地址进行访问的规范的最小示例是什么?

(此外,这在 2018 年是一个特别不安全的想法的原因是什么?)

在我回答你的问题之前,我想说的是,使用防火墙规则而不是程序本身来限制对应用程序的访问可能更实际,但我离题了。

为了回答您的问题,在查看杜松子酒后 godoc reference I found that the context struct 包含一个 ClientIp() 方法:

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.

因此,如果您设置了在应用程序中进行 IP 过滤,您可以根据该方法返回的值进行过滤。

使用 Github 页面上给出的基本示例:

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
}