【问题标题】:How to return valid jsonapi response using google/jsonapi and echo framework如何使用 google/jsonapi 和 echo 框架返回有效的 jsonapi 响应
【发布时间】:2017-06-14 20:00:59
【问题描述】:

下面的代码返回两个连接的 JSON 字符串和错误的内容类型 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())
})

有什么想法吗?

【问题讨论】:

    标签: go json-api go-echo


    【解决方案1】:

    你的代码看起来不错。但是可以简化-

    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
    

    【讨论】:

    • 谢谢!我使用了方法 1。我更新了您的代码,因此它将返回正确的 content-type 值。 -> application/vnd.api+json
    猜你喜欢
    • 1970-01-01
    • 2015-10-11
    • 2017-03-29
    • 1970-01-01
    • 2019-05-04
    • 2020-06-06
    • 2016-05-11
    • 1970-01-01
    • 2015-12-18
    相关资源
    最近更新 更多