注意:為簡單起見,省略了所有錯誤處理代碼。我在本地處理它們,沒有產(chǎn)生錯誤。在 Golang 中,我嘗試使用下面的代碼http.Request.Body從 POST 請求中讀取 a :func readBody(req *http.Request) string { bytes, _ := httputils.DumpRequestOut(req, true) return string(bytes)}它顯示了一個非零的 Content-Length,但沒有返回任何內(nèi)容:ContentLength=413 with Body length 0. 我嘗試了下面的代碼,也沒有運氣:func readBody(req *http.Request) string { bytes, _ := ioutil.ReadAll(req.Body) return string(bytes)}它返回一個空字符串。google了下,找到了一篇關(guān)于這個問題的博客:Golang: Read from an io.ReadWriter without lost its content。我試圖遵循模式,但仍然沒有運氣:func readBody(req *http.Request) string { bodyBytes, _ := ioutil.ReadAll(req.Body) // Restore the io.ReadCloser to its original state req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // Use the content return string(bodyBytes)}有什么建議?提前致謝 :)
2 回答

大話西游666
TA貢獻1817條經(jīng)驗 獲得超14個贊
發(fā)生這種情況是因為您httputils.DumpRequestOut(req, true)
在 http 客戶端執(zhí)行請求并且正文耗盡后調(diào)用。
確保按順序執(zhí)行以下步驟:
httputils.DumpRequestOut(req, true)
resp, err :=http.DefaultClient.Do(req)
httputil.DumpResponse(res, true)
- 2 回答
- 0 關(guān)注
- 919 瀏覽
添加回答
舉報
0/150
提交
取消