使用net/http包中的Get、Head、Post等函数,但不读body,也需要去关闭它吗?

GiXuan · 2015-06-10 08:33:13 · 2225 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2015-06-10 08:33:13 的主题,其中的信息可能已经有所发展或是发生改变。

假设我只想获取一个页面的cookie信息,并关心它返回的内容,也就是不读取Response.Body,是否还需要自己去关闭一下body呢(Response.Body.Close())? 第一次上来提问,方法不对的地方请见谅。


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2225 次点击  
加入收藏 微博
4 回复  |  直到 2015-06-12 05:29:43
elvindu
elvindu · #1 · 10年之前

因该都不需要关闭手动关闭吧,下面是源码上面写的备注,说: The Server will close the request body. The ServeHTTP // Handler does not need to. Body io.ReadCloser

// Body is the request's body. // // For client requests a nil body means the request has no // body, such as a GET request. The HTTP Client's Transport // is responsible for calling the Close method. // // For server requests the Request Body is always non-nil // but will return EOF immediately when no body is present. // The Server will close the request body. The ServeHTTP // Handler does not need to. Body io.ReadCloser

源码里面有如下: func (c *conn) serve() { .... serverHandler{c.server}.ServeHTTP(w, w.req) if c.hijacked() { return } w.finishRequest() if w.closeAfterReply { if w.requestBodyLimitHit { c.closeWriteAndWait() } break } .... } 处理完毕以后标准库会自动关闭链接的。

GiXuan
GiXuan · #2 · 10年之前
elvinduelvindu #1 回复

因该都不需要关闭手动关闭吧,下面是源码上面写的备注,说: The Server will close the request body. The ServeHTTP // Handler does not need to. Body io.ReadCloser // Body is the request's body. // // For client requests a nil body means the request has no // body, such as a GET request. The HTTP Client's Transport // is responsible for calling the Close method. // // For server requests the Request Body is always non-nil // but will return EOF immediately when no body is present. // The Server will close the request body. The ServeHTTP // Handler does not need to. Body io.ReadCloser 源码里面有如下: func (c *conn) serve() { .... serverHandler{c.server}.ServeHTTP(w, w.req) if c.hijacked() { return } w.finishRequest() if w.closeAfterReply { if w.requestBodyLimitHit { c.closeWriteAndWait() } break } .... } 处理完毕以后标准库会自动关闭链接的。

你说的是服务端的关闭部分吧?如果我是作为客户端呢?

elvindu
elvindu · #3 · 10年之前
GiXuanGiXuan #2 回复

#1楼 @elvindu 你说的是服务端的关闭部分吧?如果我是作为客户端呢?

是的,上一个是服务端,如果是模拟客户端的话应该都需要关闭的。 下面是源码注释:// 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.

GiXuan
GiXuan · #4 · 10年之前
elvinduelvindu #3 回复

#2楼 @GiXuan 是的,上一个是服务端,如果是模拟客户端的话应该都需要关闭的。 下面是源码注释:` // 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.`

原来不管有没有读取Body部分都需要关闭呀,好,谢谢啦!

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传