doulu3865 2015-05-02 16:51
浏览 67
已采纳

为什么Go无法正确读取请求?

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.

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

    if err != nil {
        // handle the error
    }
}
  • 写回答

2条回答 默认 最新

  • duanchu0031 2015-05-02 18:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路