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

huangapple go评论91阅读模式
英文:

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

问题

根据文档,它指出:

> 对于服务器请求,请求体(Request Body)始终不为nil,但当没有请求体时,将立即返回EOF。

对于ContentLength,文档中指出:

> 对于客户端请求,如果Body不为nil,值为0表示未知

那么是检查ContentLength更好呢?

r *http.Request
if r.ContentLength == 0 {
  // 空请求体
}

还是检查EOF更好呢?

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

input := new(Input)

if err := json.NewDecoder(r.Body).Decode(input); err.Error() == "EOF" {
    // 空请求体
}
英文:

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
}

答案1

得分: 46

你总是需要读取请求体来了解其内容。客户端可以使用分块编码(chunked encoding)发送请求体,而不包含Content-Length,或者甚至可能出现错误,发送了Content-Length但没有请求体。客户端并不必须按照其所说的方式发送请求体。

如果你只是检查空请求体,那么EOF检查可以工作,但我仍然建议除了检查EOF字符串之外,还要检查其他错误情况。

err := json.NewDecoder(r.Body).Decode(input)
switch {
case err == io.EOF:
    // 空请求体
case err != nil:
    // 其他错误
}

你也可以在解析之前读取整个请求体:

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

或者如果你担心数据量过大:

body, err := ioutil.ReadAll(io.LimitReader(r.Body, readLimit))
英文:

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))

答案2

得分: 21

如果 http.Request().Body == http.NoBody {
// TODO.
}

英文:
if http.Request().Body == http.NoBody {
  // TODO.
}

huangapple
  • 本文由 发表于 2015年9月22日 15:28:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/32710847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定