duanpai6581 2019-04-24 12:09
浏览 97
已采纳

有没有一种好的方法可以使用Echo按IP地址过滤请求? [关闭]

I'm developing an API server with the Echo HTTP framework. I woudld like to filter some requests by IP address.

Later I can manager these URLs better.
It's my code:

func filterIP(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
    fmt.Println("c.RealIP()=", c.RealIP())
    fmt.Println("c.Path()", c.Path())
    if isFilterIp(c.RealIP(), c.Path()) {
        return echo.NewHTTPError(http.StatusUnauthorized,
            fmt.Sprintf("IP address %s not allowed", c.RealIP()))
    }

    return next(c)
}
}

func main() {
e := echo.New()

filterGroup := e.Group("/filter")
filterGroup.Use(filterIP)
filterGroup.GET("/test", func(c echo.Context) error {
    return c.String(http.StatusOK, "test filter")
})

noFilterGroup := e.Group("/noFilter")
noFilterGroup.GET("/test", func(c echo.Context) error {
    return c.String(http.StatusOK, "test no filter")
})

e.Logger.Fatal(e.Start(":1323"))
}

And i want to filter Ip address in the url's level instead of group route.
eg: if there are two path: /filter/test01 and /filter/test02,and i want to filter only test01.
Is there some good way to do this?

  • 写回答

1条回答 默认 最新

  • doue8385 2019-04-24 14:31
    关注

    You can add a middleware for this:

    func filterIP(next echo.HandlerFunc) echo.HandlerFunc {
        return func(c echo.Context) error {
            // Block requests from localhost.
            if c.RealIP() == "127.0.0.1" {
                return echo.NewHTTPError(http.StatusUnauthorized,
                    fmt.Sprintf("IP address %s not allowed", c.RealIP()))
            }
    
            return next(c)
        }
    }
    
    func main() {
        e := echo.New()
        e.Use(filterIP)
        e.GET("/", func(c echo.Context) error {
            return c.String(http.StatusOK, "Hello, World!")
        })
        e.Logger.Fatal(e.Start(":1323"))
    }
    

    It's important to use the RealIP() function, otherwise you might end up with the IP address of a proxy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启