使用 gin gonic 返回文字 JSON 的最简单方法

tri*_*m_3 8 json http go server go-gin

我正在通过为 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)
}
Run Code Online (Sandbox Code Playgroud)

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

在 node.js 和 express 中,我会执行以下操作:

return res.status(200).json({"msg":"this worked"});
Run Code Online (Sandbox Code Playgroud)

在 Go + Gin 中执行此操作的最佳方法是什么?

icz*_*cza 18

一种选择是使用Context.Data()您提供要发送的数据的位置(以及内容类型):

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

    c.Data(http.StatusOK, "application/json", jsonData)
}
Run Code Online (Sandbox Code Playgroud)

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

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

    c.Data(http.StatusOK, gin.MIMEJSON, jsonData)
}
Run Code Online (Sandbox Code Playgroud)

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

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

    c.DataFromReader(http.StatusOK,
        int64(len(jsonStr)), gin.MIMEJSON, strings.NewReader(jsonStr), nil)
}
Run Code Online (Sandbox Code Playgroud)

如果你有你的JSON作为该解决方案也适用io.Reader,例如一个os.File

  • @GwynethLlewelyn 高级 Context.JSON 很棒,但是当您已经拥有 JSON 文字 byteArray 时,这个答案非常有用,例如来自某个已经吐出 JSON 的子进程的输出。谢谢 (3认同)
  • 虽然您的所有答案在技术上都是正确的,但在 [`Context.JSON()`](https://pkg.go.dev/github.com/ gin-gonic/gin?utm_source=godoc#Context.JSON) 毫不费力地完成这项工作...... (2认同)

小智 10

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

c.JSON(http.StatusOK, gin.H{"msg":"this worked"})
Run Code Online (Sandbox Code Playgroud)

  • 由于从上下文来看,很明显 OP 使用的是 Gin Gonic 框架,因此这个答案代表了在 Gin 下执行此操作的最佳、惯用方法。严格来说,其他答案可能是“正确的”,但对于那些使用 Gin Gonic 的人来说,它们并不是“最佳实践”。 (2认同)