英文:
How to return message from goREST POST endpoint?
问题
我正在使用类似下面代码的端点:
type TestService struct {
gorest.RestService `root:"/test/"`
testPost gorest.EndPoint `method:"POST" path:"/testPost/" postdata:"map[string]string"`
}
我获取并处理了发送的数据,想要返回一个有效载荷给调用客户端,即成功/错误和一条消息。
根据文档,我无法确定如何实现这一点。尝试在函数中添加output
标签并返回任何内容,就像GET端点一样,会导致以下错误:
参数列表不匹配。找不到匹配的方法用于EndPoint:[testPost],类型:[POST]。期望的是:#func(serv DocumentService) TestPost(PostData map[string]string)#,没有返回参数。
是否可以返回有效载荷给客户端?如果不行,是否可以在成功/失败时重定向到不同的端点?
英文:
I am using an endpoint similar to the below code
type TestService struct {
gorest.RestService `root:"/test/"`
testPost gorest.EndPoint `method:"POST" path:"/testPost/" postdata:"map[string]string"`
}
I get and handle the posted data, and want to return a payload to the calling client, i.e. success/error and a message.
I cannot make out from the documentation how to achieve this, appending the output
tag and returning anything from the function as per a GET end point fails with the following error;
> Parameter list not matching. No matching Method found for
> EndPoint:[testPost],type:[POST] . Expecting: #func(serv
> DocumentService) TestPost(PostData map[string]string)# with no return
> parameters.
Is it possible to return a payload to the client? If not can I redirect to a different end point on success / failure?
答案1
得分: 2
我找到了一个方法,以防有人遇到类似的问题。
看起来你可以直接使用ResponseBuilder的实例来编写代码,所以我创建了一个新的response builder,将内容类型设置为json,并将我的response写出来!
func(serv DocumentService) TestPost(PostData map[string]string){
fmt.Printf("%+v", PostData)
rb := serv.ResponseBuilder()
rb.AddHeader("Content-Type", "application/json")
rb.Write([]byte("{type:'info', msg:'Success!'}"))
}
巧合的是,如果要通过不同的方法提供输出,你可以使用类似以下的代码:
serv.ResponseBuilder().Created("http://localhost:8787/orders-service/items/"+string(i.Id))
我在http://code.google.com/p/gorest/上找到了这个方法。
英文:
So I found a way in case anyone runs into a similar issue.
It seems you can write directly using an instance of the ResponseBuilder, so I create a new response builder, set the content type to json and write my response out!
func(serv DocumentService) TestPost(PostData map[string]string){
fmt.Printf("%+v", PostData)
rb := serv.ResponseBuilder()
rb.AddHeader("Content-Type", "application/json")
rb.Write([]byte("{type:'info', msg:'Success!'}"))
}
Co-incidentally to provide output via a different method you use something like;
serv.ResponseBuilder().Created("http://localhost:8787/orders-service/items/"+string(i.Id))
Which I found at http://code.google.com/p/gorest/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论