-2

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?

4

1 回答 1

2

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.

于 2019-04-24T14:31:22.090 回答