4 回答
TA貢獻(xiàn)1765條經(jīng)驗 獲得超5個贊
我發(fā)現(xiàn)閱讀 Go 源代碼真的很容易。如果您單擊文檔中的函數(shù),您將被帶到Error函數(shù)的源代碼:https ://golang.org/src/net/http/server.go?s=61907:61959#L2006
// 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.
func Error(w ResponseWriter, error string, code int) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
fmt.Fprintln(w, error)
}
所以如果你想返回 JSON,編寫你自己的 Error 函數(shù)很容易。
func JSONError(w http.ResponseWriter, err interface{}, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
json.NewEncoder(w).Encode(err)
}
TA貢獻(xiàn)1848條經(jīng)驗 獲得超10個贊
我的回答有點晚了,已經(jīng)有一些很好的答案了。這是我的 2 美分。
如果你想在出錯的情況下返回 JSON,有多種方法可以做到這一點。我可以列舉兩個:
編寫您自己的錯誤處理程序方法
使用go-boom圖書館
1.編寫自己的錯誤處理方法
一種方法是@craigmj 所建議的,即創(chuàng)建自己的方法,例如:
func JSONError(w http.ResponseWriter, err interface{}, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
json.NewEncoder(w).Encode(err)
}
2.使用go-boom圖書館
另一種方法是使用go-boom庫。例如,如果錯誤與找不到資源有關(guān),您可以執(zhí)行以下操作:
err := errors.New("User doesn't exist")
...
boom.NotFound(w, err)
響應(yīng)將是:
{
"error": "Not Found",
"message": ",
"statusCode": 404
}
有關(guān)更多信息,請查看go-boom. 希望有幫助。
TA貢獻(xiàn)1865條經(jīng)驗 獲得超7個贊
它應(yīng)該只是純文本。
func Error(w ResponseWriter, 錯誤字符串, 代碼 int)
錯誤使用指定的錯誤消息和 HTTP 代碼回復(fù)請求。它不會以其他方式結(jié)束請求;調(diào)用者應(yīng)確保不再對 w 進(jìn)行寫入。錯誤消息應(yīng)該是純文本。
另外我認(rèn)為您的用法http.Error不正確。當(dāng)您調(diào)用時w.Write(data),將發(fā)送響應(yīng)并關(guān)閉響應(yīng)正文。這就是為什么您從http.Error.
除了使用http.Error,您可以使用 json 發(fā)送自己的錯誤響應(yīng),就像通過將狀態(tài)代碼設(shè)置為錯誤代碼來發(fā)送任何其他響應(yīng)一樣。
TA貢獻(xiàn)1865條經(jīng)驗 獲得超7個贊
就像@ShashankV 說的那樣,您正在以錯誤的方式編寫響應(yīng)。例如,以下是我在學(xué)習(xí)使用 Golang 編寫 RESTful API 服務(wù)時所做的:
type Response struct {
StatusCode int
Msg string
}
func respond(w http.ResponseWriter, r Response) {
// if r.StatusCode == http.StatusUnauthorized {
// w.Header().Add("WWW-Authenticate", `Basic realm="Authorization Required"`)
// }
data, err := json.Marshal(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, err.Error())
return
}
w.WriteHeader(r.StatusCode)
fmt.Fprintf(w, r.Msg)
}
func Hello(w http.ResponseWriter, r *http.Request) {
resp := Response{http.StatusOK, welcome}
respond(w, resp)
}
參考:https ://github.com/shudipta/Book-Server/blob/master/book_server/book_server.go
希望,這會有所幫助。
- 4 回答
- 0 關(guān)注
- 215 瀏覽
添加回答
舉報
