登录
首页 >  Golang >  Go问答

学习如何使用适当的JSON响应消息格式进行发送

来源:stackoverflow

时间:2024-02-07 21:45:22 132浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《学习如何使用适当的JSON响应消息格式进行发送》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我有一个 go 程序,我想打印 json 响应消息:

func mypluginfunction(w http.responsewriter, r *http.request) {
  data := `{"status":"false","error":"bad request"}`
  w.header().set("content-type", "application/json")
  w.writeheader(http.statusbadrequest )
  json.newencoder(w).encode(data)
}

但是,当我使用这个函数时,我得到了一个奇怪的 json 格式。它看起来像这样:

"{\"status\":\"false\",\"error\":\"bad request\"}"

有没有办法让响应消息变成普通的json,例如:

{
  "status": "false",
  "error": "bad request"
}

正确答案


您的 data 已包含 json 编码数据,因此您应该按原样编写,无需重新编码:

func mypluginfunction(w http.responsewriter, r *http.request) {
    w.header().set("content-type", "application/json")
    w.writeheader(http.statusbadrequest )
    data := `{"status":"false","error":"bad request"}`
    if _, err := io.writestring(w, data); err != nil {
        log.printf("error writing data: %v", err)
    }
}

如果将 data 传递给 encoder.encode(),它会被视为“常规”字符串,并按此方式进行编码,从而生成一个 json 字符串,其中双引号根据 json 规则进行转义。

如果您有非 json go 值,则只需进行 json 编码,如下例所示:

func MyPluginFunction(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusBadRequest)

    data := map[string]any{
        "status": "false",
        "error":  "bad request",
    }
    if err := json.NewEncoder(w).Encode(data); err != nil {
        log.Printf("Error writing data: %v", err)
    }
}

今天关于《学习如何使用适当的JSON响应消息格式进行发送》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>