所以我有这样的类型

type TextTagRelationship struct {
  Id int64 `json:"id"`
  TagId int64 `json:"tag_id"`
  TaggedText string `json:"tagged_text"`
  TagName string `json:"tag_name"`
  PageNumber int64 `json:"page_number"`
  Color string `json:"color"`
}

type TextTagRelationships []TextTagRelationship

现在,我有一个处理程序,可以执行以下操作
func getTaggedTextForPage(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    pageNumber, err := strconv.ParseInt(vars["pageNumber"], 10, 64)
    check(err)
    defer r.Body.Close()
    rows, err := db.Query("SELECT * from tagged_text WHERE page_number = ?", pageNumber)
    check(err)
    var textTagRelationships []TextTagRelationship
    var textTagRelationship TextTagRelationship
    for rows.Next() {
        //execute sql code here
        textTagRelationships = append(textTagRelationships, textTagRelationship)
    }


    if err := json.NewEncoder(w).Encode(textTagRelationships); err != nil {
        check(err)
    }
}

如果有实际的行,这可以很好地工作,但是在对空数组textTagRelationships进行编码时,在chrome控制台的响应中,我得到了null。为什么会这样呢?看起来textTagRelationships实际上是[],因此我希望编码可以编码[],而我的响应也带有[]

最佳答案

看起来这是Go中的陷阱。

https://danott.co/posts/json-marshalling-empty-slices-to-empty-arrays-in-go.html

解决此问题的方法是不依赖默认的初始化行为,而是实际执行make
var textTagRelationships TextTagRelationships = make(TextTagRelationships, 0)

07-24 09:51