你能在 golang http.Error 中返回 json 吗?

调用时可以返回 jsonhttp.Error吗?


        myObj := MyObj{

            MyVar: myVar}


        data, err := json.Marshal(myObj)

        if err != nil {

            http.Error(w, err.Error(), http.StatusInternalServerError)

            return 

        }

        w.Write(data)

        w.Header().Set("Content-Type", "application/json")


        http.Error(w, "some error happened", http.StatusInternalServerError)

我看到它200没有返回,json但 json 被嵌入text


慕村225694
浏览 173回答 4
4回答

POPMUISE

我发现阅读 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)}

慕桂英546537

我的回答有点晚了,已经有一些很好的答案了。这是我的 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. 希望有帮助。

莫回无

它应该只是纯文本。来自文档func Error(w ResponseWriter, 错误字符串, 代码 int)错误使用指定的错误消息和 HTTP 代码回复请求。它不会以其他方式结束请求;调用者应确保不再对 w 进行写入。错误消息应该是纯文本。另外我认为您的用法http.Error不正确。当您调用时w.Write(data),将发送响应并关闭响应正文。这就是为什么您从http.Error.除了使用http.Error,您可以使用 json 发送自己的错误响应,就像通过将状态代码设置为错误代码来发送任何其他响应一样。

鸿蒙传说

就像@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希望,这会有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go