我正在通过为 Web 服务器构建一个简单的 API 接口(interface)来学习 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 中执行此操作的最佳方法是什么?
最佳答案
一种选择是使用 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)
}
如果您的数据以字符串
值的形式提供并且很大,您可以使用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 - 使用 gin gonic 返回文字 JSON 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56664328/