我正在尝试编写一个方法,该方法将返回一个可以满足json.Marshaler接口的函数。我的推理是提供结构的不同表示。也许我正在接近这个完全错误的。func (api *Api) SiteList(c *gin.Context) { var sites []db.Site if err := api.db.Find(&sites).Error; err != nil { } var payload []json.Marshaler for _, site := range sites { payload = append(payload, site.ToApi()) } c.JSON(http.StatusOK, payload)}我从这个函数得到的结果是列表中的项目数量正确,但每个项目的值相同:[ { "key": "NZ7LCA9HQN3", "name": "autumn-waterfall-1573" }, { "key": "NZ7LCA9HQN3", "name": "autumn-waterfall-1573" }, { "key": "NZ7LCA9HQN3", "name": "autumn-waterfall-1573" }, { "key": "NZ7LCA9HQN3", "name": "autumn-waterfall-1573" }, { "key": "NZ7LCA9HQN3", "name": "autumn-waterfall-1573" }]最后,这是ToApi实现:type EncoderFunc func() ([]byte, error)func (fn EncoderFunc) MarshalJSON() ([]byte, error) { return fn()}func (site *Site) ToApi() json.Marshaler { return EncoderFunc(func() ([]byte, error) { var payload public.Site payload.Name = site.Name payload.Key = site.Key data, err := json.Marshal(payload) if err != nil { return nil, err } return data, nil })}
1 回答
- 1 回答
- 0 关注
- 186 浏览
添加回答
举报
0/150
提交
取消