go - returning an empty array if the database is empty -


the front end of application expects json returned server under namespace (like messages below)

{    messages: [{        "id": "6b2360d0" //other properties omitted     },{        "id": "a01dfaa0" //other properties omitted     }] } 

if there no messages, need return empty array namespace

{      messages: [] } 

however, code below returns null if no messages pulled db

{          messages: null     } 

how can change code below

  {          messages: []     } 

is returned if there no messages in db?

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()          k, v := c.last(); k != nil && index < 10; k, v = c.prev() {           //note next few lines might appear odd, each  json object added array of messages namespaced under 'message', first unmarshal map , unmarshal again 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)  } 

replace:

    var ib inbox 

with:

    var ib inbox     ib.messages = make([]*message, 0) 

or with:

    ib := inbox{messages: make([]*message, 0)} 

(optionally using make(…, 0, someinitialcapacity) instead.)


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -