我的應(yīng)用程序的前端期望 json 從命名空間下的服務(wù)器返回(如下messages所示){ messages: [{ "id": "6b2360d0" //other properties omitted },{ "id": "a01dfaa0" //other properties omitted }]}如果沒有消息,我需要返回一個(gè)帶有命名空間的空數(shù)組{ messages: []}但是,null如果沒有從數(shù)據(jù)庫中提取消息,下面的代碼當(dāng)前會返回{ messages: null }如何更改下面的代碼,以便 { messages: [] }如果數(shù)據(jù)庫中沒有消息,則返回?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)}
如果數(shù)據(jù)庫為空,則返回一個(gè)空數(shù)組
炎炎設(shè)計(jì)
2021-10-11 10:33:03