为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕村225694 2022-05-05 17:44:09
调用时可以返回 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
查看完整描述

4 回答

?
POPMUISE

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)

}


查看完整回答
反对 回复 2022-05-05
?
慕桂英546537

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. 希望有帮助。



查看完整回答
反对 回复 2022-05-05
?
莫回无

TA贡献1865条经验 获得超7个赞

它应该只是纯文本。

来自文档

func Error(w ResponseWriter, 错误字符串, 代码 int)

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

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

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


查看完整回答
反对 回复 2022-05-05
?
鸿蒙传说

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


希望,这会有所帮助。


查看完整回答
反对 回复 2022-05-05
  • 4 回答
  • 0 关注
  • 172 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号