rest - golang中多次请求后多次关闭响应体

标签 rest http go request response

this post ,指出response.Body应该关闭,避免资源泄漏。它也显示在 http package godoc 中的概述示例中。 .

在我的测试代码中,我发送多个请求来尝试使用 API

resp, err := http.DefaultClient.Do(req)

在同一个函数中多次。这是一个不好的做法吗?在这种情况下,我是在每个之后编写 defer resp.Body.Close() 还是只编写一次?

url := server.URL + "/ticket/add"                                       
reader = strings.NewReader(`{"id": "test1", "detail": "test1"}`)        
req, err := http.NewRequest("POST", url, reader)                        
assert.Nil(t, err)               

resp, err := http.DefaultClient.Do(req)                                 
assert.Nil(t, err)                                                      

defer resp.Body.Close()                                                 

assert.Equal(t, http.StatusCreated, resp.StatusCode)                    
// add a ticket with same id                                            
reader = strings.NewReader(`{"id": "test1"}`)                           
req, err = http.NewRequest("POST", url, reader)                         
assert.Nil(t, err)                                                      

resp, err = http.DefaultClient.Do(req)                                  
assert.Nil(t, err)                                                      
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)   

一个相关的问题,在服务器端,即在func(w http.ResponseWriter, r *http.Request)内部,是否也需要关闭请求正文?

最佳答案

是的,您需要关闭这两个回复。推迟对 resp.Body.Close 的一个调用不会以某种方式影响另一个调用。 *http.Response 在每种情况下都不同,并且它们都可以延迟。

在服务器端,您不需要从 http.Request documentation 关闭 Request.Body - :

// The Server will close the request body. The ServeHTTP
// Handler does not need to.

关于rest - golang中多次请求后多次关闭响应体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383622/

相关文章:

python - 从 BaseHTTPServer 解析 Python HTML POST 数据

rest - 如何将某些功能分组到特定线程中并在 KarateDSL 中并行运行

php - Paypal PHP REST API - 结账时不显示付款金额

c# - dot Net Core MVC 中的 HttpMethodAttribute 存在奇怪的歧义

java - 带有代理的 Java 中的 HTTP 基本身份验证

node.js - 为什么 Node.js 无法提供 .woff 文件

asp.net-mvc-3 - MVC3 Restful 版本控制路由

go - vert 提示func文字捕获了循环变量

google-app-engine - appengine dev_appserver 时间奇怪

go - 从 Twitter 库搜索中获取数据到 Go 中的结构