go - Cannot defer close request body
问题描述
Any idea why I cannot close request body? Request is returning 200
and no error but req.Body.Close()
is throwhing runtime error: invalid memory address or nil pointer dereference
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!
解决方案
The application should close the response body, not the request body:
defer resp.Body.Close()
The req.Body
field is set from the last argument to http.NewRequest
. The req.Body
field is nil because the last argument to http.NewRequest
is nil.
The transport closes the request body (if it's not nil) per the documentation for Request.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.
推荐阅读
- arrays - 无法使用 perl 以数组形式划分 csv 文件的每一行
- sql - 用于更改列的红移窗口函数
- html - Angular - 仅禁用表格中的一行
- amazon-web-services - 我可以使用 aws-cli 分配角色吗?
- javascript - 努力使联系表格在使用 PHP 的网站上工作
- spring - 用户 Bean 作为实体和普通 Bean
- javascript - 所有特殊字符代码都不会使用 Domsanitizer 转换为相应的符号
- sql - 如何在oracle sql中获取2个字符之间的值
- apache-spark - Zeppelin Spark Interpreter:从 Spark Structured Streaming 写入的 HDFS 数据中读取时禁用 _spark_metadata
- python - 如何根据熊猫中的某些条件比较 df1 中的一行与 df2 中的其他行?