gpt4 book ai didi

http - 检查空请求正文的最佳方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 13:03:53 25 4
gpt4 key购买 nike

来自 documentation它指出

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

对于 ContentLength,文档说明

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

那么检查 ContentLength 是否更好

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

或检查EOF

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

input := new(Input)

if err := json.NewDecoder(r.Body).Decode(input); err.Error() == "EOF" {
//empty body
}

最佳答案

您总是需要阅读正文才能知道内容是什么。客户端可以在没有 Content-Length 的情况下以分 block 编码发送正文,或者它甚至可能有错误并发送 Content-Length 而没有正文。客户没有义务发送它所说的要发送的内容。

EOF 检查可以在您只检查空正文时起作用,但我仍然会检查除了 EOF 字符串之外的其他错误情况。

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

您还可以在解码之前阅读整个正文:

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

或者如果您担心数据过多

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

关于http - 检查空请求正文的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com