4 回答

TA贡献1765条经验 获得超5个赞
我发现阅读 Go 源代码真的很容易。如果您单击文档中的函数,您将被带到Error函数的源代码: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 函数很容易。
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贡献1848条经验 获得超10个赞
我的回答有点晚了,已经有一些很好的答案了。这是我的 2 美分。
如果你想在出错的情况下返回 JSON,有多种方法可以做到这一点。我可以列举两个:
编写您自己的错误处理程序方法
使用go-boom图书馆
1.编写自己的错误处理方法
一种方法是@craigmj 所建议的,即创建自己的方法,例如:
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库。例如,如果错误与找不到资源有关,您可以执行以下操作:
err := errors.New("User doesn't exist")
...
boom.NotFound(w, err)
响应将是:
{
"error": "Not Found",
"message": ",
"statusCode": 404
}
有关更多信息,请查看go-boom. 希望有帮助。

TA贡献1865条经验 获得超7个赞
就像@ShashankV 说的那样,您正在以错误的方式编写响应。例如,以下是我在学习使用 Golang 编写 RESTful API 服务时所做的:
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 关注
- 172 浏览
添加回答
举报