我有一个链 claw http.Handler
中间件,我的第一个处理程序可能会在其中写入错误响应:
http.Error(w, err.Error(), http.StatusUnauthorized)
但是我的其他中间件继续执行,但我不希望它继续执行。最好的方法是什么?我尝试在调用 http.Error()
后检查状态 header ,看看它是否不是 200:
status := w.Header().Get("Status")
但是状态是一个空字符串。
最佳答案
您可以在错误发生后立即使用“裸”return
来停止中间件链的执行。
来自 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.
从这里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
}
.../...
}
关于google-app-engine - 中间件错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39285029/