我无法在 Revel Go 框架中发布正文

Alv*_*sta 2 rest curl go revel

我正在尝试使用 Rest 架构实现基本的 CRUD,但是我无法将json格式编码的数据发送到端点,我尝试了多种方法来检查请求中的正文内容,所以现在我有一个“最小可编译示例”:

  1. 使用 revel cli 工具创建一个新项目。

  2. 应用以下更改

    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
    
    Run Code Online (Sandbox Code Playgroud)
  3. 做一个POST请求:

    curl --request POST --header "Content-Type: application/json" --header "Accept: application/json" --data '{"name": "Revel framework"}' http://localhost:9000
    
    Run Code Online (Sandbox Code Playgroud)

我的问题; curl 调用没有给我回声(相同json {"name": "Revel framework"}),所以我缺少正确使用 revel 的东西?

PS:我可以找到一些其他与此问题相关的链接,但它们对我不起作用。例如这个:https : //github.com/revel/revel/issues/126

ymo*_*nad 5

根据Revel来源,当请求内容类型为application/jsonor 时text/json,会自动从 stream 中读取请求体的内容并存储到类型为 的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)
}
Run Code Online (Sandbox Code Playgroud)