2017-06-13 82 views
0

下面的代码返回两个级联的JSON字符串和一个错误的内容类型text/plain。应该是application/vnd.api+json如何使用google/jsonapi和echo框架返回有效的jsonapi响应

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 
} 

错误输出(两个级联的jsons)。第一个是正确的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()) 
}) 

任何想法?

回答

1

你是代码看起来没问题。但是它可以simplified-

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 
+0

谢谢!我使用了方法1.我更新了代码,以便它返回正确的“内容类型”值。 - >'application/vnd.api + json' – michaelbn

+0

不客气。谢谢。 – jeevatkm