I am trying to write a method that will return a function that can satisfy the json.Marshaler
interface. My reasoning is to provide different representations of the struct. Perhaps I am approaching this completely wrong.
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)
}
The result I get from this function is the correct number of items in the list, but the same value for each:
[
{
"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"
}
]
Finally, here is the ToApi
implementation:
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
})
}