Reputation: 1839
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
Upvotes: 28
Views: 46218
Reputation: 2979
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
Upvotes: 51