下面的代码返回两个简明的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())
})

任何的想法?

最佳答案

您的代码看起来还不错。但是,它可以简化-

var b bytes.Buffer // you could use buffer pool here
err := jsonapi.MarshalManyPayload(&b, albumList())
if err != nil {
    return err
}
return c.JSONBlob(http.StatusOK, b.Bytes())

以下是您的想法的方法:

方法1-
c.Response().Header().Set(echo.HeaderContentType, jsonapi.MediaType)
c.Response().WriteHeader(http.StatusOK)
return jsonapi.MarshalManyPayload(c.Response(), albumList())

方法2-
var b bytes.Buffer // you could use buffer pool here
err := jsonapi.MarshalManyPayload(&b, albumList())
if err != nil {
    return err
}
c.Response().Header().Set(echo.HeaderContentType, jsonapi.MediaType)
c.Response().WriteHeader(http.StatusOK)
_, err := b.WriteTo(c.Response())
return err

关于go - 如何使用Google/jsonapi和echo框架返回有效的jsonapi响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44515677/

10-09 15:11