1
我的應用程序的前端準備被來自服務器的命名空間下返回的JSON(如下面messages
)返回一個空數組如果數據庫是空
{
messages: [{
"id": "6b2360d0" //other properties omitted
},{
"id": "a01dfaa0" //other properties omitted
}]
}
如果沒有消息,我需要與命名空間
{
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)
}
即,雖然'nil'片具有['len'](https://godoc.org/builtin#len)0,它與長度爲零的「實際」/非零片不同沒有零容量無關緊要,除了追加)。 –