gocraft / web

Go Router + Middleware. Your Contexts.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

a little fault of middleware in the subrouter, or solution needed.

lightingland opened this issue · comments

func init() {
rootRouter := web.New(Context{}).Middleware((_Context).LoginRequired)
adminRouter := rootRouter.Subrouter(AdminContext{}, "/admin")
adminRouter.Middleware((_AdminContext).AdminRequired)
// http.Handle("/", rootRouter)
}

I'm trying gocraft in google's app engine. For the code above I found it's a bit unexpected results for me because only LoginRequired middleware been called when I go url "..../admin". I expect the AdminRequired middleware been called too since I've subrouter it.
Add this code:
/*
adminRouter.Get("/", (*AdminContext).Handler)
*/
should work just like sample code. But I expect AdminRequired been called in any of http methods even I don't have the matching handlers. Sounds reasonable?

commented

Your code is very poorly formatted. Perhaps if you cleaned it up some we could read it.

Well, I tried format it as gofmt does. And add in the post. seems it's all I can do now. Only middleware calls as smiple as in the gocraft example.

commented

I can't replicate the behavior you are describing. Take a look at https://gist.github.com/hydrogen18/0523d40f6983923bf0cd

When I use curl to hit the "/admin" route it works as expected. Both middleware instances are called.

ericu@ericu-desktop:~$ go run gocraft_issue_35.go
A GET /admin
B GET /admin

As you can see both middleware instances were called for the same request.

@lightingland The 2nd middleware isn't called because you don't have any handlers, so routing isn't done yet, so it never gets tot he adminRouter. See the Request Lifecycle in the Reademe.

Sounds it working just like the name says, only when in the 'middle', not as tail. Good point.
Of cause I have no doubt with http get handler appended. my point is I don't have planty handlers matching http methods like POST, PUT, DELETE and more. Is it a bit strange if the client invokes these methods to "/admin" but without subrouter middleware being called?

In my case I want to log the ip into the blacklist when they illegally touch "/admin" five times in any other http methods. Ideas?

If you want middleware to execute in 404 situations (no handler), the middleware has to be on the root router. You can look at the request.URL.Path in the middleware to see if it has a url prefix.

Closing this out, lmk if you'd like more guidance.