在golang中的多个请求之后多次关闭响应正文 [英] Close response body multiple times after multiple requests in golang
问题描述
在此帖 ,有人指出应该关闭响应体,以避免资源泄露。它也显示在 http包godoc 的概述示例中。
在我的测试代码中,我发送了多个请求来尝试一个API
resp,err: = http.DefaultClient.Do(req)
多次在同一个函数中。这是一种不好的做法吗?在这种情况下,我是不是每个人都写了 defer res.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)
//添加一张具有相同标识的票据
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
在每种情况下都不相同,并且它们都可以被延迟。
在服务器端,您不需要关闭 Request.Body
- http.Request
文档:
//服务器将关闭请求主体。 ServeHTTP
// Handler不需要。
In this post, it is pointed out that response.Body should be closed to avoid resource leak. It is also shown in the overview examples in http package godoc.
In my test code, I send multiple requests to try an API with
resp, err := http.DefaultClient.Do(req)
multiple times in the same function. Is this a bad practice? In this case, do I write defer resp.Body.Close()
after each of them, or just once?
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)
A related question, on the server side, i.e., inside the func(w http.ResponseWriter, r *http.Request)
, is it necessary to close the request body as well?
Yes, you need to close both responses. Deferring one call to resp.Body.Close
does not somehow effect the other. The *http.Response
is different in each case, and they both can be deferred.
On the server side, you do not need to close the Request.Body
-- from the http.Request
documentation:
// The Server will close the request body. The ServeHTTP
// Handler does not need to.
这篇关于在golang中的多个请求之后多次关闭响应正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!