Skip to content

net/http: Client can't close HTTP stream. #3672

Closed
@dustin

Description

@dustin
I can't seem to close an HTTP response body while it's still sending data.  I ran into
this in an app I was writing, but I believe the following client and server demonstrate
the problem (sorry, not sure how to write a trustworthy test for this):


// server.go:

package main

import (
    "log"
    "net/http"
    "time"
)

func foreverYoung(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-type", "application/javascript")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.WriteHeader(200)

    for {
        w.Write([]byte("young\r\n"))
        w.(http.Flusher).Flush()
        time.Sleep(time.Second)
    }
}

func main() {
    http.HandleFunc("/", foreverYoung)
    log.Fatal(http.ListenAndServe(":4334", nil))
}




// client.go:

package main

import (
    "log"
    "net/http"
    "os"
)

func main() {
    resp, err := http.Get("http://localhost:4334/";)
    if err == nil {
        func() {
            defer resp.Body.Close()
            for {
                b := []byte{0}
                _, err := resp.Body.Read(b)
                if err != nil {
                    log.Fatalf("Error reading stuff: %v", err)
                }
                os.Stdout.Write(b)
                if b[0] == byte('\n') {
                    return
                }
            }
        }()
    } else {
        log.Fatalf("Error in stream: %v", err)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions