dongliao3450 2018-10-20 15:42
浏览 316

golng获取url和resp.Body.Close()

I am looking for go code to fetch url and in most of the cases this the code for fetching url on go :

func main() {
    for _, url := range os.Args[1:] {
        resp, err := http.Get(url)
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: %v
", err)
            os.Exit(1)
        }
        b, err := ioutil.ReadAll(resp.Body)
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: reading %s: %v
", url, err)
            os.Exit(1)
        }
        fmt.Printf("%s", b)
    }
}

my question why needed here resp.Body.Close() and whay this exactly doing ?

  • 写回答

2条回答 默认 最新

  • dongzhong7299 2018-10-20 16:06
    关注

    If you dig into the http docs https://golang.org/pkg/net/http/

    The Get method used to make the resp is a Response

     func (c *Client) Get(url string) (resp *Response, err error)
    

    In the Response source:

            // Body represents the response body.
            //
            // The response body is streamed on demand as the Body field
            // is read. If the network connection fails or the server
            // terminates the response, Body.Read calls return an error.
            //
            // The http Client and Transport guarantee that Body is always
            // non-nil, even on responses without a body or responses with
            // a zero-length body. It is the caller's responsibility to
            // close Body. The default HTTP client's Transport may not
            // reuse HTTP/1.x "keep-alive" TCP connections if the Body is
            // not read to completion and closed.
            //
            // The Body is automatically dechunked if the server replied
            // with a "chunked" Transfer-Encoding.
            Body io.ReadCloser
    

    So the Close() tidies up the resources that are used to get the Body

    If this isn't done the Response (resp) won't be able to do "keep-alive" and I guess there is a chance that some of the resources in the Response won't be able to be recycled

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。