dqde43215 2017-10-05 06:45
浏览 979
已采纳

Golang无法从request.GetBody()获取正文

I try to read the request body via request.GetBody(), since I need to read the same request body more than once, but I always get the error below. I checked if the req.body is empty, but it is not. I cant even call req.GetBody(). My Go version is 1.8.1.

 func read(res http.ResponseWriter, req *http.Request) {

     _, err := req.GetBody()
    if err != nil {
        res.Write([]byte(err.Error()))
        return
    }

}

Error:

http: panic serving [::1]:53174: runtime error: invalid memory address or nil pointer dereference
  • 写回答

2条回答 默认 最新

  • drtppp75155 2017-10-05 07:38
    关注

    The GetBody() func on Request is only for client requests (see the documentation over the GetBody member: https://golang.org/pkg/net/http/#Request), but it looks like you're doing a server-side handler. Therefore, you need to use the req.Body member, which is an io.ReadCloser. To read from an io.ReadCloser you can use the io/ioutil package and the ReadAll() func:

    b, err := ioutil.ReadAll(req.Body)
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("%s", b)
    

    More information on the ReadAll() func: https://golang.org/pkg/io/ioutil/#example_ReadAll

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路