2017-09-03 63 views
2

我試圖在Revel中使用Rest架構來實現一個基本的CRUD,但是我不能將json格式編碼的數據發送到端點,我嘗試了多種方法檢查請求中的正文內容,所以現在我有一個「最小可編譯示例」:我不能在Revel中獲得張貼的身體去框架

  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 
    
  3. 做一個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"}),所以我錯過了正確使用陶醉?

PS:我可以找到一些其他相關的鏈接到這個問題,但他們不適合我。例如,這:https://github.com/revel/revel/issues/126

回答

2

根據該source of Revel,當請求的內容類型爲application/jsontext/json,請求主體的內容被自動地從流讀出並存儲到c.Params.JSON其類型[]byte

由於Request.Body是一次只能讀一個流,你可以不讀一遍(反正,你的代碼甚至不會工作,如果狂歡不會自動讀取流,因爲c.Request.Body是不正確serialiazable使用c.RenderJSON() )。

狂歡有便利的功能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) 
}