我正在構建一個 http api 并且我的每個處理程序都返回 JSON 數據,因此我構建了一個包裝器函數來處理 JSON 編組和 http 響應(我已經包含了包裝器中的相關部分以及示例處理程序之一以下)。傳遞任意嵌套結構的最佳方法是什么(結構還包含任意類型/數量的字段)?,F在我已經確定了一個帶有字符串鍵和 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}
- 1 回答
- 0 關注
- 213 瀏覽
添加回答
舉報
0/150
提交
取消