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

Simplest way to return literal JSON using gin gonic

我正在通过为 Web 服务器构建一个简单的 API 界面来学习 Go。当命中默认路由时,我想 return 在 JSON 中发送一条简单消息。

到目前为止,在线阅读,这是对 return 文字 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中表达,我会做这样的事情:

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

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

一种选择是使用 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 值可用并且很大,您可以避免将其转换为 []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)
}

如果您将 JSON 作为 io.Reader, e.g. an os.File

,此解决方案也适用

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

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