知道为什么我无法关闭请求正文吗?请求返回200且没有错误,但是req.Body.Close()抛出运行时错误:无效的内存地址或nil指针取消引用
clientHttp := &http.Client{}
req, err := http.NewRequest("GET", "https://example.com/item/"+strconv.FormatInt(itemID, 10), nil)
if err != nil {
logrus.Error(err)
return models.Company{}, err
}
resp, err := clientHttp.Do(req)
if err != nil {
logrus.Error(err)
return models.Company{}, err
}
defer req.Body.Close() // <- panic!
Run Code Online (Sandbox Code Playgroud)
应用程序应关闭响应主体,而不是请求主体:
defer resp.Body.Close()
Run Code Online (Sandbox Code Playgroud)
该req.Body字段从最后一个参数设置为http.NewRequest。该req.Body字段为nil,因为to的最后一个参数http.NewRequest为nil。
传输将根据Request.Body的文档关闭请求正文(如果不是nil) :
对于客户端请求,nil主体表示该请求没有主体,例如GET请求。HTTP客户端的传输负责调用Close方法。
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |