首页 > 解决方案 > 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!

标签: gorequest

解决方案


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.


推荐阅读