下面的代码返回两个连接的 JSON 字符串和一个错误的 content-type text/plain
。应该application/vnd.api+json
package main
import (
"github.com/google/jsonapi"
"github.com/labstack/echo"
"net/http"
)
type Album struct {
ID int `jsonapi:"primary,albums"`
Name string `jsonapi:"attr,name"`
}
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
jsonapi.MarshalManyPayload(c.Response(), albumList())
return c.JSON(http.StatusOK, c.Response())
})
e.Logger.Fatal(e.Start(":1323"))
}
func albumList() []*Album {
a1 := Album{123, "allbum1"}
a2 := Album{456, "allbum2"}
albums := []*Album{&a1, &a2}
return albums
}
错误的输出(两个连接的 json)。第一个是正确的jsonapi
结构,我认为第二个与echo-framework
:
{
"data": [
{
"type": "albums",
"id": "123",
"attributes": {
"name": "allbum1"
}
},
{
"type": "albums",
"id": "456",
"attributes": {
"name": "allbum2"
}
}
]
}
{
"Writer": {},
"Status": 200,
"Size": 133,
"Committed": true
}
此代码解决了问题,但似乎很尴尬。我觉得有更好的方法来促进它使用echo
.
e.GET("/", func(c echo.Context) error {
var b bytes.Buffer
body := bufio.NewWriter(&b)
err := jsonapi.MarshalManyPayload(body, albumList())
if err != nil {
fmt.Println(err)
}
body.Flush()
return c.JSONBlob(http.StatusOK, b.Bytes())
})
任何的想法?