BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11673

returning an empty array if the database is empty

The front end of my application expects json to be returned from the server under a namespace (like messages below)

{
   messages: [{
       "id": "6b2360d0" //other properties omitted

   },{
       "id": "a01dfaa0" //other properties omitted

   }]
}

If there are no messages, I need to return an empty array with the namespace

{

    messages: []
}

However, the code below currently returns null if no messages are pulled from the db

{

        messages: null
    }

How can I change the code below so that

  {

        messages: []
    }

is returned if there are no messages in the 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()

        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)

}

Upvotes: 1

Views: 3963

Answers (1)

Dave C
Dave C

Reputation: 7896

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.)

Upvotes: 6

Related Questions