为什么Go不能正确读取请求?

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

Why couldn't Go read a request properly?

问题

我的API需要解析传入的请求。在第一步中,数据需要由Go的ioutil包的ReadAll()函数读取。为什么会出现错误?

官方文档没有给出提示,因为没有描述此类错误的原因。

func ParseRequest(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)

    if err != nil {
        // 处理错误
    }
}
英文:

My API needs to parse incoming requests. In the first step, the data needs to be read by Go's ReadAll() function of the ioutil package. Why should there an error occur?

The official documentation does not give a hint, because the reasons for such an error aren't described.
<!-- language: lang-go -->

func ParseRequest(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)

    if err != nil {
        // handle the error
	}
}

答案1

得分: 4

ioutil.ReadAll 可能因为多种原因而失败。它能够读取任何 io.Reader,而不仅仅是 HTTP 请求体。而 Request.Body 只是一个 io.ReadCloser。我完全可以生成一个与网络套接字以外的其他内容相关联的 io.ReadCloser(我经常使用这种方法来构建代理和隧道协议)。

很明显,许多种类的 io.Reader 事件可能会出现错误(例如,您可能无法访问文件,或者在读取文件的过程中磁盘可能被卸载)。特别是在 HTTP 方面,您可能会遇到网络故障错误。如果网络套接字在读取请求体的过程中收到 RST 数据包,您会期望发生什么?

然而,最重要的是,您必须处理错误,因为 Reader 接口可能会生成错误。不要对该接口的实现方式做任何假设。

英文:

ioutil.ReadAll can fail for many reasons. It is capable of reading any io.Reader, not just an HTTP request body. And Request.Body is just an io.ReadCloser. It is totally legal for me to generate one that is tied to things other than the network socket (I do these kinds of things to http all the time to build proxies and tunneling protocols).

It should be obvious that many kinds of io.Reader events can have errors (you may not have access to a file for instance, or the disk may be unmounted half-way through reading it). Specific to HTTP, you might similarly expect network failure errors. What would you expect to happen if the network socket received a RST packet half-way through reading the request body?

Ultimately, though, the point you should take away is that you must deal with errors because the Reader interface can generate errors. Do not make assumptions about how that interface is implemented.

答案2

得分: 0

如果客户端发送了无效的 JSON,那是客户端的错误:"400 Bad Request"。

如果 JSON 是有效的,但服务器代码存在错误,那是服务器的错误:"500 Internal Server error"。

英文:

If the client did send invalid JSON, it is the clients fault: 400 Bad Request.

If the JSON was valid but the server code contains a bug, its the servers fault: 500 Internal Server error.

huangapple
  • 本文由 发表于 2015年5月3日 00:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/30004945.html
匿名

发表评论

匿名网友

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

确定