【问题标题】:Simplest way to return literal JSON using gin gonic使用 gin gonic 返回文字 JSON 的最简单方法
【发布时间】:2019-11-01 23:54:41
【问题描述】:

我正在通过为 Web 服务器构建一个简单的 API 接口来学习 Go。当命中默认路由时,我想以 JSON 格式返回一条简单消息。

到目前为止,在线阅读,这是返回文字 JSON 字符串,并将其编码并发送给用户的最简单方法。

func GetDefault(c *gin.Context)  {
    jsonData := []byte(`{"msg":"this worked"}`)

    var v interface{}
    json.Unmarshal(jsonData, &v)
    data := v.(map[string]interface{})  

    c.JSON(http.StatusOK,data)
}

这是最有效/最快的方法吗?

在 node.js 和 express 中,我会做类似的事情:

return res.status(200).json({"msg":"this worked"});

在 Go + Gin 中最好的方法是什么?

【问题讨论】:

  • c.JSON(http.StatusOK, map[string]string{"msg":"this worked"}) 更接近 node.js 示例。
  • @mkopriva 询问者已准备好 JSON 响应作为 string 值。
  • @icza 我注意到,但是节点中的{"msg":"this worked"} 不是字符串文字,而是一个对象。所以我推断如果他们可以在节点中使用一个对象,为什么不能在 go 中使用地图?
  • 是的,不一定需要是字符串,示例 node.js 代码就是我的目标。无需使用预定义结构即可轻松构建的对象。

标签: json http go server go-gin


【解决方案1】:

一种选择是使用Context.Data(),您可以在其中提供要发送的数据(连同内容类型):

func GetDefault(c *gin.Context)  {
    jsonData := []byte(`{"msg":"this worked"}`)

    c.Data(http.StatusOK, "application/json", jsonData)
}

您也可以为内容类型使用常量:

func GetDefault(c *gin.Context)  {
    jsonData := []byte(`{"msg":"this worked"}`)

    c.Data(http.StatusOK, gin.MIMEJSON, jsonData)
}

如果您的数据可用作string 值并且很大,如果您使用Context.DataFromReader(),则可以避免将其转换为[]byte

func GetDefault(c *gin.Context) {
    jsonStr := `{"msg":"this worked"}`

    c.DataFromReader(http.StatusOK,
        int64(len(jsonStr)), gin.MIMEJSON, strings.NewReader(jsonStr), nil)
}

如果您的 JSON 格式为 io.Reader,此解决方案也适用,例如一个os.File

【讨论】:

    【解决方案2】:

    您可以在响应中使用gin.H 结构:

    c.JSON(http.StatusOK, gin.H{"msg":"this worked"})
    

    【讨论】:

      猜你喜欢
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2020-09-05
      • 2015-09-04
      相关资源
      最近更新 更多