如何在gorest EndPoint语法中提供JSON对象ID以输出数据?

huangapple go评论88阅读模式
英文:

How to provide JSON Object ID in gorest EndPoint syntax for output data?

问题

我对Go和GoRest还不熟悉,但我有关于它的问题。

如何在gorest EndPoint语法中提供JSON对象ID以描述下面的输出数据?

我有一个简单的例子:

type HelloService struct {
    gorest.RestService `root:"/api" consumes:"application/json" produces:"application/json"`
    playList    gorest.EndPoint `method:"GET" path:"/list/" output:"[]Item"`
    playItem    gorest.EndPoint `method:"PUT" path:"/go/{Id:int}" postdata:"Item"`
}


func(serv HelloService) PlayList() []Item{
    serv.ResponseBuilder().SetResponseCode(200)
    return itemStore

}


type Item struct{
    Id              int
    FileName        string
    Active          bool
}

var(
    itemStore []Item
)

结果的JSON是:

[{"Id":1,"FileName":"test :1","Active":false},{"Id":2,"FileName":"test :2","Active":false}, ... ]

但是,Mustache.js无法解析它,因为它需要首先有对象ID。
Mustache想要这样的东西:

{
 "repo": [{"Id":1,"FileName":"test :1","Active":false},{"Id":2,"FileName":"test      
:2","Active":false}, ... ]
}
英文:

I'm new to Go and GoRest, but I have question regarding it.

How to provide JSON Object ID in gorest EndPoint syntax for output data described below?

I have simple example:

type HelloService struct {
    gorest.RestService `root:"/api" consumes:"application/json" produces:"application/json"`
    playList    gorest.EndPoint `method:"GET" path:"/list/" output:"[]Item"`
    playItem    gorest.EndPoint `method:"PUT" path:"/go/{Id:int}" postdata:"Item"`
}


func(serv HelloService) PlayList() []Item{
    serv.ResponseBuilder().SetResponseCode(200)
    return itemStore

}


type Item struct{
    Id              int
    FileName        string
    Active          bool
}

var(
    itemStore []Item
)

And the resulting JSON Is:

[{"Id":1,"FileName":"test :1","Active":false},{"Id":2,"FileName":"test :2","Active":false}, ... ]

But,Mustache.js can't parse it because it needs object ID first.
Mustache wants something like this:

{
 "repo": [{"Id":1,"FileName":"test :1","Active":false},{"Id":2,"FileName":"test      
:2","Active":false}, ... ]
}

答案1

得分: 3

你可能需要更改

playList gorest.EndPointmethod:"GET" path:"/list/" output:"[]Item"`

playList gorest.EndPointmethod:"GET" path:"/list/" output:"ItemStore"`

var(
    itemStore []Item
)

type ItemStore struct {
	Items []Item
}

var(
    itemStore ItemStore
)

一个完整的可工作程序会更容易调试。

英文:

You probably need to change

playList gorest.EndPointmethod:"GET" path:"/list/" output:"[]Item"`

to
playList gorest.EndPointmethod:"GET" path:"/list/" output:"ItemStore"`

and

var(
    itemStore []Item
)

to

type ItemStore struct {
	Items []Item
}

var(
    itemStore ItemStore
)

A complete working program would be much easier to debug.

huangapple
  • 本文由 发表于 2012年12月17日 20:11:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/13913935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定