案例
例如,有個 GET 接口,可以批量獲取用戶信息👇
> curl 'http://localhost:8080/user/1,2,3'
[
{
"user_id":1,
"other_suff":...
},
{
"user_id":2,
"other_suff":...
},
{
"user_id":3,
"other_suff":...
}
]
同時,我們要將用戶信息和他們的某些訂單信息放在一起,組裝成為👇的接口,滿足其他業務需求。
[
{
"user_info":{
"user_id":1,
"other_suff":...
},
"order_info":{
"order_id":1,
"user_id":1,
"other_suff":...
}
},
{
"user_info":{
"user_id":2,
"other_suff":...
},
"order_info":{
"order_id":2,
"user_id":2,
"other_suff":...
}
},
{
"user_info":{
"user_id":3,
"other_suff":...
},
"order_info":{
"order_id":3,
"user_id":3,
"other_suff":...
}
}
]
分析
解決這個問題很簡單:把user信息和order信息的json用工具解析得到結構體,然后調用他們的接口得到數據,根據id關聯和拼裝,最后返回。
這樣的做法存在的一個問題是,代碼解析了user和order的完整結構。如果user接口返回的用戶信息增加了字段,我們這里的結構體要同步更新,否則我們給出的數據就是不完整的。(這可能是很痛苦的,你要求別的團隊加字段,得排期...)
其實我們作為數據的“中間商”,只關心user接口json里的 user_id ,我們使用這個字段關聯order數據。對于user信息里的 other_suff 或者其他數據,我們并不關心,只要保證完整傳出去就好了。
根據 https://golang.org/pkg/encoding/json/#Unmarshal ,可以知道直接丟一個 map[string]interface{} 給 json.Unmarshal 也可以正常解析的,于是我們可以寫出比較通用的透傳代碼。
type Content []map[string]interface{}
func (c Content) GetByFieldName(name string, defaultVal interface{}) infterface{} {
for _, item := range c {
val, ok := item[name]
if !ok {
continue
}
if val == nil {
return defaultVal
}
return val
}
return defaultVal
}
func getUserContentByIDs(ids []int) Content {
...
var c Content
err := json.Unmarshal(jsonData, c)
...
return c
}
func getOrderContentByUserIDs(ids []int) Content {.../*同上*/}
func Handler(userIDs []int) []Combine {
users := getUserContentByIDs(userIDs)
orders := getOrderContentByUserIDs(userIDs)
// 這里假設用戶和訂單是一對一的關系
ret := make([]Combine, 0, len(users))
for _, u := range users {
for _, o := range orders {
userID := u.GetByFieldName("user_id", 0)
orderUserID := o.GetByFieldName("user_id", 0)
if userID != 0 userID == orderUserID {
ret = append(ret, Combine{
UserInfo: u,
OrderInfo: o,
})
break
}
}
}
return ret
}
P.S. 在上面的例子中,每次查詢Content都要遍歷數組。如果數據量大或者查詢頻繁,可以在初始化Content的時候,根據item的唯一標標識,再給Content根據封裝一個map,提高查詢效率。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- Golang map如何生成有序的json數據詳解
- go語言中json數據的讀取和寫出操作