作为一个官方库肯定是要考虑到所有场景的,就像上面说的视频,或者还有很多需要不断读取的场景。 至于 Close 哪个的话这个就另说了,我个人感觉 Close body 好像合理一点。 顺便提醒下楼上的,defer 前一定要检查 body 是不是 nil ,不然如果 body 出现 nil 的情况,defer 执行的时候我记得是会 panic 的
lvlongxiang199
2024-02-01 08:22:36 +08:00
我觉得很合理. `resp.Body` 就是个 reader 跟 fileReader 类似, 区别就是这是别人帮你 open 然后把 ownership move 给你, 负责 close 是用户的事, 你觉得 fileReader 必须 close 是不是合理的 ? 虽然对于大部分调用 rest api 的情况, 是把 reader 内的读出来, 之后 close. 但是对于需要流式获取的场景并不合适(比如: 实时视频流, 大文件), 按我的理解, 进入标准库的东西, 得适配普遍的场景, 而非 rest api 这种单一场景
crackidz
2024-02-01 08:33:28 +08:00
语法糖也是要关闭的,只是不需要你手工关闭而已。response 对象的话包含了很多的其他内容,即使允许 close response 也能读取其中的其他信息,这其实很反直觉的。
看文档,至少官方实现 Body 不会出现 nil 的情况. 我一直没检查过 body 是否为 nil
Body represents the response body. The response body is streamed on demand as the Body field is read. If the network connection fails or the server terminates the response, Body.Read calls return an error. The http Client and Transport guarantee that Body is always non-nil, even on responses without a body or responses with a zero-length body. It is the caller's responsibility to close Body. The default HTTP client's Transport may not reuse HTTP/1.x "keep-alive" TCP connections if the Body is not read to completion and closed.