Iris: Match trailing slash in the URL

Created on 22 Nov 2017  Â·  2Comments  Â·  Source: kataras/iris

hi @kataras
how to handle trailing space, I am always getting 404
http://localhost:8080/route/

app.Post("/route/", func(ctx iris.Context) {
ctx.JSON(iris.Map{"result": "pass"})
})

help-needed

Most helpful comment

I disagree with your point of view, nearly all the API I know of accept requests ending with a trailing slash. To workaround iris throwing 301 or 404, you can add this just after your app := iris.New():

    app.WrapRouter(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
        path := r.URL.Path
        if len(path) > 1 && path[len(path)-1] == '/' && path[len(path)-2] != '/' {
            path = path[:len(path)-1]
            r.RequestURI = path
            r.URL.Path = path
        }
        next(w, r)
    })

This removes any traliling slash if there is only one and the request is not /, before passing it to iris.

All 2 comments

You don't have to and it's not correct to register /route/ as route paths, if you learn this on any previous web framework you used, it's wrong. Iris will match the request path /route/ to the /route route, so you don't have to manually register that. There is an option for DisablePathCorrection but if you set that to true, this will just give 404 for /route/ in order to give you the option to manually handle this error.

I disagree with your point of view, nearly all the API I know of accept requests ending with a trailing slash. To workaround iris throwing 301 or 404, you can add this just after your app := iris.New():

    app.WrapRouter(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
        path := r.URL.Path
        if len(path) > 1 && path[len(path)-1] == '/' && path[len(path)-2] != '/' {
            path = path[:len(path)-1]
            r.RequestURI = path
            r.URL.Path = path
        }
        next(w, r)
    })

This removes any traliling slash if there is only one and the request is not /, before passing it to iris.

Was this page helpful?
0 / 5 - 0 ratings