我正在通过为 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 中执行此操作的最佳方法是什么?