相关疑难解决方法(0)

如果我不关闭响应会发生什么.在golang身上?

在Golang我有一些http响应,我有时忘记打电话:

resp.Body.Close()
Run Code Online (Sandbox Code Playgroud)

在这种情况下会发生什么?会有内存泄漏吗?defer resp.Body.Close()获取响应对象后立即放入是否安全?

client := http.DefaultClient
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
    return nil, err
}
Run Code Online (Sandbox Code Playgroud)

如果有错误怎么办,可能resp或者resp.Body是零?

go

66
推荐指数
3
解决办法
3万
查看次数

如果在调用http.Get(url)时发生错误,是否需要关闭响应对象?

在以下代码中,还需要在错误情况下关闭响应主体:

res, err := http.Get(url)

if err != nil {
    log.Printf("Error: %s\n", err)
}

defer res.Body.Close()
Run Code Online (Sandbox Code Playgroud)

error-handling http go deferred

12
推荐指数
1
解决办法
1939
查看次数

标签 统计

go ×2

deferred ×1

error-handling ×1

http ×1