2 回答

TA貢獻1829條經驗 獲得超6個贊
這沒有什么竅門。當您希望處理函數停止執行操作時,只需從函數返回即可:
func testRest(w http.ResponseWriter, rest string) {
if rest == "abc" {
http.Error(w, "The go-routine should stop here", 500)
return
}
fmt.Print("This shouldn't be printed")
}
如果你想記錄一些東西,記錄一些東西:
func testRest(w http.ResponseWriter, rest string) {
if rest == "abc" {
http.Error(w, "The go-routine should stop here", 500)
log.Println("something bad happened")
return
}
fmt.Print("This shouldn't be printed")
}
這里的所有都是它的。當你說“內部錯誤不會停止請求的處理”時,你似乎認為發生了更多的魔法,但在 Go 中卻很少有魔法。http.Error將錯誤響應寫回客戶端。就這樣。它沒有辦法“阻止”任何事情;它只是將狀態代碼和正文寫入客戶端連接,然后返回。返回后,您有機會在調用代碼中執行更多操作,但如果您只想返回函數,則只需返回即可。從處理程序返回是“停止處理請求” - 您的代碼正在處理請求,您擁有完全的控制權。
- 2 回答
- 0 關注
- 184 瀏覽
添加回答
舉報