Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang cant get body from request.GetBody()

Tags:

go

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
like image 562
jona jürgen Avatar asked Oct 05 '17 06:10

jona jürgen


People also ask

How do you read request body in go?

Inspecting and mocking request body One option is to read the whole body using ioutil. ReadAll() , which gives you the body as a byte slice. You may use bytes. NewBuffer() to obtain an io.

How do you read a response body in Golang?

To read the body of the response, we need to access its Body property first. We can access the Body property of a response using the ioutil. ReadAll() method. This method returns a body and an error.

Can get have a body?

GET requests don't have a request body, so all parameters must appear in the URL or in a header. While the HTTP standard doesn't define a limit for how long URLs or headers can be, mostHTTP clients and servers have a practical limit somewhere between 2 kB and 8 kB.

Do we need to close Request body in Golang?

You must close the Body (if present) on all code paths you might take. You probably do not want to close the Body before having processed it (or at least parts of it).


1 Answers

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

like image 87
PaulJ Avatar answered Oct 22 '22 11:10

PaulJ