-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?

Shaco
  • 11
  • 1
  • 3
  • 1
    What is "go echo frame"? If you have a server of some sort, you must have some access to the remote ip address. – JimB Apr 24 '19 at 12:12
  • it's go-echo.I can get the remote ip address and i want make a separate module filter ip instead of coding in the service logic codes .Is there some good middleware to filter ip? – Shaco Apr 24 '19 at 12:24
  • Please show an example of what you're trying to do, preferably with a [mcve] if you've encountered a problem. The Echo framework is designed around composing middleware, so it would seem you already have what you're looking for. – JimB Apr 24 '19 at 12:30

1 Answers1

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.

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146