今天golang报了个错:
下面代码将报错,提示
golang http panic: runtime error: invalid memory address or nil pointer dereference
resp, _ := http.Get(url)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
正确的应是:defer resp.Body.Close() 应在 ioutil.ReadAll之后
resp, _ := http.Get(url)
body, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
另外,关于defer的使用规则,这里篇文章说的就很清楚:
https://www.cnblogs.com/vikings-blog/p/7099023.html
本文介绍了 Golang 中处理 HTTP 请求时的一个常见错误:在读取响应体之前就关闭了它,这会导致运行时错误。文章提供了正确的代码示例,并推荐了一篇关于 defer 使用规则的文章。
432

被折叠的 条评论
为什么被折叠?



