3 ms·
Middlewares force you to use a Go context to pass data, which has its own downsides. I personally much prefer passing data explicitly — through function composi
by atombender 7y ago
Middlewares force you to use a Go context to pass data, which has its own downsides. I personally much prefer passing data explicitly — through function composition and structs and so on — to contexts.
- jerf 7y agoSpecific "middleware libraries" may; the general concept does not. The general concept is just to wrap a decorator around an http.Handler with something else that implements http.Handler. You don't need any sort of specialized "middleware support"; all Go interfaces already support being decorated. I have found that there is a bit of a misconception in the Go community that there's something special about http.Handler and that you need lots of special code to deal with it. I've seen the misconception that "middleware" is something special and that you can only do it to http.Handlers a lot, but a "middleware" is just "a decorator applied to http.Handler". You can decorate any interface value the same way. There's also a misconception that "routers" are something special, like, they have their own type or something. But they aren't. They're just http.Handlers that can examine a request and figure out which other http.Handler to call. One thing I do a lot is wrap my top-level logger around the "router" that is the top level of my website; in one shot, you decorated the entire website. It's all just http.Handlers, there's no "real" distinction.
- atombender 7y agoRight, I was specifically referring to routers like Chi where you attach middlewares to a "mux". These don't rely on function composition, and so the only way to pass information onwards — loggers, sessions, and so on — is to use contexts. The community has a lot of nice middlewares that do things like basic auth, session management, cache headers, etc. If you use decorators and not middlewares, you'll have to write your own middleware code.