Charles L. Charles L. - 8 months ago 44
HTTP Question

How to break a chunked in go using net/http?

I have an http server with an endpoint that returns lots of data streamed from a db. The response is chunked (

< Transfer-Encoding: chunked
). And if I run into an error, like the DB crashing, I can use a panic & curl will warn me of an issue:

curl: (18) transfer closed with outstanding read data remaining

I don't want a panic though - I just want a simple log message. And if I
I don't get the error in curl so there's no indication of something breaking.

Is there a way to break an chunked http response without a panic?


That error you want is because the connection was closed by the http server. In order to force the connection closed without a panic, you will have to hijack it:

// inside the http handler
// func(w http.ResponseWriter, r *http.Request) {

// to abort an HTTP/1.1 response
if w, ok := w.(http.Hijacker); ok {
    c, _, err := w.Hijack()
    if err != nil {
        log.Println("cannot close connection:", err)