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

3

33

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
}
Sacellum answered 22/9, 2015 at 7:28 Comment(2)
Clearly EOF, Content-Length is a header that the client can or cannot set.Lap
Don't muck with the string value of errors. If you're looking for io.EOF then do if err == io.EOF. Looking at the string representation is at best incredibly fragile.Jewel
K
47

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))
Kemberlykemble answered 22/9, 2015 at 13:23 Comment(0)
O
25
if http.Request().Body == http.NoBody {
  // TODO.
}
Ojeda answered 30/7, 2019 at 18:44 Comment(1)
That method does not exist in http, we can access the Body field from the Request type: pkg.go.dev/net/http#Request insteadInae
K
0

I know this is old, and this isn't Go Fiber question, but I have the same problem and this is the top post whenever I search it. So if anyone is having this problem when using BodyParser, you can validate a nil body with

func NotEmptyBody(c *fiber.Ctx) bool {
    return len(c.Body()) != 0
}

An Empty struct will have still have a list of bytes, while a nil body will contain empty bytes. You can validate this first before calling Bodyparser.

Kerch answered 28/7 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.