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

use*_*010 3 go

http.Error调用时可以返回json吗?

        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)
Run Code Online (Sandbox Code Playgroud)

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

cra*_*gmj 11

我发现阅读 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)
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您想返回 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)
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*k V 5

它应该只是纯文本。

来自文档

func 错误(w ResponseWriter,错误字符串,代码整数)

错误回复带有指定错误消息和 HTTP 代码的请求。它不会以其他方式结束请求;调用者应确保不会对 w 进行进一步的写入。错误消息应该是纯文本。

另外我认为你的用法http.Error不正确。当您调用 时w.Write(data),将发送响应并关闭响应正文。这就是为什么您从http.Error.

除了使用http.Error,您可以使用 json 发送自己的错误响应,就像通过将状态代码设置为错误代码来发送任何其他响应一样。