Reputation: 6958
I have a chain of claw http.Handler
middlewares, where my first handler might write an error response:
http.Error(w, err.Error(), http.StatusUnauthorized)
However my other middlewares continue executing, but I don't want it to. What is the best way to go about this? I tried checking the status header after calling http.Error()
, to see if it is other than a 200:
status := w.Header().Get("Status")
but status is an empty string.
Upvotes: 0
Views: 811
Reputation: 2246
You can use a "naked" return
just after your error to stop the middleware chain execution.
From http documentation:
Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.
From this Custom Handlers and Avoiding Globals in Go Web Applications :
func myHandler(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "myapp")
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return // Forget to return, and the handler will continue on
}
.../...
}
Upvotes: 1