我正在尝试解组 HTTP REST API 请求的结果,该请求根据结果的数量返回一个对象或一个对象数组。
请求是通用的,因为我试图围绕特定的 REST API 构建一个包装器,它被称为:
// Function prototype where I am trying to convert the response
func (client *Client) Get(endpoint string, data map[string]string) (map[string]json.RawMessage, error)
// The way the function is called
client.Get("/v1/users", map[string]string{"filter.abc": "lorem ipsum"})
两个响应示例:
[
{
"abc": "def",
"efg": 123
"hij": [
{
"klm": "nop"
}
]
},
{
"abc": "def",
"efg": 123
"hij": [
{
"klm": "nop"
}
]
}
]
// RESPONSE 1: Array of JSON objects that have child arrays
{
"abc": "def",
"efg": 123
"hij": [
{
"klm": "nop"
}
]
}
// RESPONSE 2: In this case, only one element was returned.
我已经实现了仅针对响应 2 执行此操作,如下所示:
// [...]
byteBody = ioutil.ReadAll(res.Body)
// [...]
var body map[string]json.RawMessage
if err := json.Unmarshal(byteBody, &body); err != nil { [...] }
那么,最惯用的解析方式是什么?有没有办法避免编写冗余代码并解析两个响应?我正在考虑将响应放入的“模型”作为附加参数。这是一个好习惯吗?非常感谢您!
湖上湖
呼唤远方
相关分类