我正在尝试使用 revel 中的 Rest 架构实现基本的 CRUD,但我无法将以 json
格式编码的数据发送到端点,我尝试了多种方法来检查请求中的正文内容,所以现在我有一个“最小可编译示例”:
使用 revel cli 工具创建一个新项目。
应用以下更改
diff --git a/app/controllers/app.go b/app/controllers/app.go index 1e94062..651dbec 100644 --- a/app/controllers/app.go +++ b/app/controllers/app.go @@ -9,5 +9,6 @@ type App struct { } func (c App) Index() revel.Result { - return c.Render() + defer c.Request.Body.Close() + return c.RenderJSON(c.Request.Body) } diff --git a/conf/routes b/conf/routes index 35e99fa..5d6d1d6 100644 --- a/conf/routes +++ b/conf/routes @@ -7,7 +7,7 @@ module:testrunner # module:jobs -GET / App.Index +POST / App.Index # Ignore favicon requests GET /favicon.ico 404
执行 POST 请求:
curl --request POST --header "Content-Type: application/json" --header "Accept: application/json" --data '{"name": "Revel framework"}' http://localhost:9000
我的问题; curl 调用没有给我回显(相同的 json
{"name": "Revel Framework"}
),那么我缺少什么来正确使用 revel 呢?
PS:我可以找到一些与此问题相关的其他链接,但它们对我不起作用。例如:https://github.com/revel/revel/issues/126
最佳答案
根据source of Revel ,当请求内容类型为 application/json
或 text/json
时,会自动从流中读取请求正文的内容并存储到 c.Params.JSON其类型为 []byte
。
自 Request.Body是一个只能读取一次的流,您无法再次读取它(无论如何,即使 Revel 不会自动读取流,您的代码也将无法工作,因为 c.Request.Body
不是使用c.RenderJSON()
可正确序列化。
Revel有便捷的功能Params.BindJSON它将 c.Params.JSON 转换为 golang 对象。
这是示例代码。
type MyData struct {
Name string `json:"name"`
}
func (c App) Index() revel.Result {
data := MyData{}
c.Params.BindJSON(&data)
return c.RenderJSON(data)
}
关于rest - 我无法在 revel go 框架中发布正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46028723/