以下是如何在 Go 中正确关闭 HTTP 请求的示例:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("http://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close() // 确保在函数结束前关闭 Body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body))
}
在这个例子中,defer resp.Body.Close()
确保在函数返回前关闭响应的 Body
。defer
语句会将函数的执行推迟到包围它的函数即将退出时执行。
package main
import (
"fmt"
"io/ioutil"
"net/http"
"time"
)
func main() {
client := &http.Client{
Timeout: time.Second * 10, // 设置超时时间
}
req, err := http.NewRequest("GET", "http://example.com", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close() // 确保在函数结束前关闭 Body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body))
}
关闭 HTTP 响应的 Body
是防止资源泄漏的关键步骤,应该在每次使用 HTTP 请求时都这样做。