Reputation: 3436
What is the correct behaviour for an http server if an error occurs while writing a streaming response to the client. The client has already received status code 200 so it thinks it is okay. Can the server still terminate the connection in such a way to notify the client that an error occurred or should it return something in the response body?
I am streaming many rows from a database so I would prefer not to batch before sending to client.
An example in golang:
func streamingHandler(s ServerSettings, db *sql.DB) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json-seq")
w.Header().Set("Access-Control-Allow-Origin", "*")
_, err = fmt.Fprintf(w, "\u001E[1,2,3]\n", item)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
_, err = fmt.Fprintf(w, "\u001E[1,2,3]\n", item)
// the error could be from Fprintf or a database error.
// What happens if error occurs here.. the client has already received header and some response
if err != nil {
http.Error(w, err.Error(), 500)
return
}
...
etc
})
}
Upvotes: 1
Views: 1609
Reputation: 30496
I'm afraid you'll have to add a protocol upon the protocol. Like using ajax, sending short json responses with your own OK/Continue/Abort status messages.
There is nothing in HTTP to handle that (there is something with the 100-Continue in client to server, badly implmented and not made for server to client), unless maybe sending chunked responses and never sending the last chunk (so the whole response will timeout).
With the ajax solution you'll also be able to start showing the results before the end.
Managing you own chunks upon HTTp is usually the simpliest solution, see for exampe the file uploaders, they will split files in chunks using js and recompose the file server-side.
Trying to manage all the mess that a reverse proxy or a proxy could inject in your big HTTP messages communications (think that until recently Nginx reverse proxy would not stream responses, and use a buffered message).
Upvotes: 2