如果数据库为空,则返回一个空数组。

huangapple go评论83阅读模式
英文:

returning an empty array if the database is empty

问题

我的翻译如下:

我的应用程序的前端期望从服务器返回一个带有命名空间的 JSON(如下所示的 messages)。

{
   "messages": [{
       "id": "6b2360d0" //其他属性省略

   },{
       "id": "a01dfaa0" //其他属性省略
     
   }]
}

如果没有消息,我需要返回一个带有命名空间的空数组。

{
    "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() {

            //注意下面几行可能看起来有点奇怪,当前要添加到消息数组中的每个 JSON 对象也是在 'message' 下的命名空间中,所以我首先将其解组为一个 map,然后再解组为结构体
            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(ib)
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(response)

}
英文:

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

{
   messages: [{
       &quot;id&quot;: &quot;6b2360d0&quot; //other properties omitted

   },{
       &quot;id&quot;: &quot;a01dfaa0&quot; //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:&quot;messages&quot;`
}
type Message struct {
	Content string `json:&quot;type&quot;`
	Date string `json:&quot;date&quot;`
	Id   string `json:&quot;id&quot;`
}

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(&quot;messages&quot;)).Cursor()

		for k, v := c.Last(); k != nil &amp;&amp; index &lt; 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 &#39;message&#39;, 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, &amp;objmap); err != nil {
				return err
			}
			
			message := &amp;Message{}
			if err := json.Unmarshal(*objmap[&quot;message&quot;], &amp;message); err != nil {
				return err
			}
			
			ib.Messages = append(ib.Messages, message)

		}

		return nil
	})

	response, _ := json.Marshal(a)
	w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
	w.WriteHeader(http.StatusOK)
	w.Write(response)

}

答案1

得分: 6

将:

    var ib Inbox

替换为:

    var ib Inbox
    ib.Messages = make([]*Message, 0)

或者替换为:

    ib := Inbox{Messages: make([]*Message, 0)}

(可选择使用make(…, 0, someInitialCapacity)来指定初始容量)。

英文:

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

huangapple
  • 本文由 发表于 2015年5月31日 02:01:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/30549522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定