3 ms·
> Instead of duplicating code to implement common/middleware functionality, I like to just pass around functions. The problem there is that it doesn't allow yo
by elithrar 12y ago
> Instead of duplicating code to implement common/middleware functionality, I like to just pass around functions.
The problem there is that it doesn't allow you to either:
• Apply the middleware to routers or sub-routers;
• You end up with http.HandleFunc("/", loggingMiddleware(recoveryMiddleware(sessionMiddleware(myHandler)))) - which is no fun, repetitive and prone to errors
• There's no request context - your handlers have no way to communicate between themselves (i.e. passing a CSRF token from middleware to the handler rendering the template or writing to the response header)
It does work for basic applications, but it just doesn't scale beyond more than a (small) handful of routes. I wrote a little function[1] that helps with avoiding the gratuitous function nesting, but you'll need to BYO request context in many cases. This often ends up being map[string]interface{} (so you may want getters/setters to wrap types coming in and out), as the alternative is to rely on structs + methods (ala https://github.com/gocraft/web https://github.com/gocraft/web) which can be a little unwieldy. Horses for courses, as they say!
[1]: https://gist.github.com/elithrar/21cb76b8e29398722532 https://gist.github.com/elithrar/21cb76b8e29398722532