2 回答

TA貢獻1829條經(jīng)驗 獲得超6個贊
這沒有什么竅門。當您希望處理函數(shù)停止執(zhí)行操作時,只需從函數(shù)返回即可:
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")
}
這里的所有都是它的。當你說“內(nèi)部錯誤不會停止請求的處理”時,你似乎認為發(fā)生了更多的魔法,但在 Go 中卻很少有魔法。http.Error將錯誤響應(yīng)寫回客戶端。就這樣。它沒有辦法“阻止”任何事情;它只是將狀態(tài)代碼和正文寫入客戶端連接,然后返回。返回后,您有機會在調(diào)用代碼中執(zhí)行更多操作,但如果您只想返回函數(shù),則只需返回即可。從處理程序返回是“停止處理請求” - 您的代碼正在處理請求,您擁有完全的控制權(quán)。
- 2 回答
- 0 關(guān)注
- 183 瀏覽
添加回答
舉報