4 ms·
> the mitigation is relatively straightforward by using custom handlers like mentioned at the end, if needed. Why not implement ServeHTTP on the custom handler
by masklinn 4y ago
> the mitigation is relatively straightforward by using custom handlers like mentioned at the end, if needed.
Why not implement ServeHTTP on the custom handler though? That's not exactly difficult:
type MyHandlerFunc func(w http.ResponseWriter, r *http.Request) error
func (f MyHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := f(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Then you can just register it with
http.Handle("/hello", MyHandlerFunc(someHandler))
- andrewstuart2 4y agoThere are definitely edge cases here (like what if the handler already wrote a body and it was sent on the wire, etc), but this is absolutely the pattern to use, and one of my favorite parts of a type system that allows methods on function types.
- catlifeonmars 4y agoYes, or what if you want to upgrade the connection to a websocket?
- skrtskrt 4y agoActually a bunch of router/web helper libraries do this in different ways which makes it a huge pain to compose middleware from different libraries. Even Mux's middleware library is not consistent in how it does this for different middlewares so they have to be applied different ways or even have wrapper functions written
- catlifeonmars 4y agoThis. Middlewares typically expect to wrap an http.Handler so you lose all the middleware composition ergonomics by adding a return value to your custom handler signature
- masklinn 4y agoHere it just implements the standard library’s interface rather than use some sort of conversion closure adapter, there’s nothing special to it.