【发布时间】:2013-07-25 14:54:39
【问题描述】:
我正在构建一个 http api,我的每个处理程序都返回 JSON 数据,因此我构建了一个处理 JSON 编组和 http 响应的包装器函数(我已经包含了包装器中的相关部分以及其中之一下面的示例处理程序)。
传递任意嵌套结构的最佳方式是什么(结构还包含任意类型/字段数量)。现在我已经确定了一个带有字符串键和 interface{} 值的地图。这行得通,但这是最惯用的方法吗?
result := make(map[string]interface{})
customerList(httpRequest, &result)
j, err := json.Marshal(result)
if err != nil {
log.Println(err)
errs := `{"error": "json.Marshal failed"}`
w.Write([]byte(errs))
return
}
w.Write(j)
func customerList(req *http.Request, result *map[string]interface{}) {
data, err := database.RecentFiftyCustomers()
if err != nil {
(*result)["error"] = stringifyErr(err, "customerList()")
return
}
(*result)["customers"] = data//data is a slice of arbitrarily nested structs
}
【问题讨论】:
-
我认为 map[string]interface{} 是个好主意。但是,地图已经是引用,您不需要使用指针。
-
太棒了,想想小费。
-
查看 Andrew Gerrand 的博文“JSON and Go” (blog.golang.org/json-and-go)。特别是“解码任意数据”部分。
标签: go