Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check for empty request Body?

Tags:

http

go

From the documentation it states that

For server requests the Request Body is always non-nil but will return EOF immediately when no body is present.

For ContentLength, the documentation states

For client requests, a value of 0 means unknown if Body is not nil.

So is it better to check for ContentLength

r *http.Request
if r.ContentLength == 0 {
  //empty body
}

or to check EOF

type Input struct {
    Name *string `json:"name"`
}

input := new(Input)

if err := json.NewDecoder(r.Body).Decode(input); err.Error() == "EOF" {
 //empty body
}
like image 418
Sanath Ballal Avatar asked Sep 22 '15 07:09

Sanath Ballal


People also ask

How do I check if a REQ is empty in node?

body is empty, it returns an empty object, as such, making ! req. body return false even when it's empty. Instead, you should test for !

What is the body of a request?

A request body is data sent by the client to your API. A response body is the data your API sends to the client. Your API almost always has to send a response body. But clients don't necessarily need to send request bodies all the time.


2 Answers

You always need to read the body to know what the contents are. The client could send the body in chunked encoding with no Content-Length, or it could even have an error and send a Content-Length and no body. The client is never obligated to send what it says it's going to send.

The EOF check can work if you're only checking for the empty body, but I would still also check for other error cases besides the EOF string.

err := json.NewDecoder(r.Body).Decode(input) switch { case err == io.EOF:     // empty body case err != nil:     // other error } 

You can also read the entire body before unmarshalling:

body, err := ioutil.ReadAll(r.Body) 

or if you're worried about too much data

body, err := ioutil.ReadAll(io.LimitReader(r.Body, readLimit)) 
like image 120
JimB Avatar answered Nov 11 '22 14:11

JimB


if http.Request().Body == http.NoBody {
  // TODO.
}
like image 26
Muhammad Salem Avatar answered Nov 11 '22 12:11

Muhammad Salem