I’m learning http in go and in following code I forget defer resp.Body.Close()
but the whole code still run through without any issue. I know this line is to close http.get returned body after the entire program complete. but I’m wondering what’s the concequence without this line of code, since I didn’t see any difference.
package main
import (
"bufio"
"fmt"
"net/http"
)
func main() {
resp, err := http.Get("http://gobyexample.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("Response status:", resp.Status)
scanner := bufio.NewScanner(resp.Body)
for i := 0; scanner.Scan() && i < 5; i++ {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}
}