Http question in golang

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 (

func main() {

    resp, err := http.Get("")
    if err != nil {
    defer resp.Body.Close()

    fmt.Println("Response status:", resp.Status)

    scanner := bufio.NewScanner(resp.Body)
    for i := 0; scanner.Scan() && i < 5; i++ {

    if err := scanner.Err(); err != nil {

In your particular case that line don’t care because closing the program, after a timout, the associated tcp connection will stop.
Is important in applications having many requests (eg. concurent requests) because each of them open a file descriptor in operating system for each tcp connection. So, closing the connection will close the file descriptor otherwise under many concurent requests you can run very quick out of descriptors.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.