我有一系列claw echo 'You have: ' . Money::Add($coin1, $coin2) . '<br>';
个中间件,我的第一个处理程序可能会写错误响应:
http.Handler
然而,我的其他中间件继续执行,但我不希望它。最好的方法是什么?我在调用http.Error(w, err.Error(), http.StatusUnauthorized)
后尝试检查状态标头,看看它是否不是200:
http.Error()
但状态为空字符串。
答案 0 :(得分:1)
您可以在错误发生后使用“裸”return
来停止中间件链的执行。
错误使用指定的错误消息和HTTP代码回复请求。否则不会结束请求;调用者应确保不再对w进行进一步写入。错误消息应该是纯文本。
从此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
}
.../...
}