我的应用程序的前端期望 json 从命名空间下的服务器返回(如下messages所示)
{
messages: [{
"id": "6b2360d0" //other properties omitted
},{
"id": "a01dfaa0" //other properties omitted
}]
}
如果没有消息,我需要返回一个带有命名空间的空数组
{
messages: []
}
但是,null如果没有从数据库中提取消息,下面的代码当前会返回
{
messages: null
}
如何更改下面的代码,以便
{
messages: []
}
如果数据库中没有消息,则返回?
type Inbox struct {
Messages []*Message `json:"messages"`
}
type Message struct {
Content string `json:"type"`
Date string `json:"date"`
Id string `json:"id"`
}
func fetchMessages(w http.ResponseWriter, req *http.Request) {
var ib Inbox
var index int = 0
err := db.View(func(tx *bolt.Tx) error {
c := tx.Bucket([]byte("messages")).Cursor()
for k, v := c.Last(); k != nil && index < 10; k, v = c.Prev() {
//note the next few lines might appear odd, currently each json object to be added to the array of messages is also namespaced under 'message', so I first unmarshal it to a map and then unmarshal again into a the struct
var objmap map[string]*json.RawMessage
if err := json.Unmarshal(v, &objmap); err != nil {
return err
}
message := &Message{}
if err := json.Unmarshal(*objmap["message"], &message); err != nil {
return err
}
ib.Messages = append(ib.Messages, message)
}
return nil
})
response, _ := json.Marshal(a)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(response)
}
呼唤远方
相关分类