StreamingJSON does nothing / information in README is false
dannyvankooten opened this issue · 1 comments
The README states the following:
By default, Render does not stream JSON to the http.ResponseWriter. It instead marshalls your object into a byte array, and if no errors occurred, writes that byte array to the http.ResponseWriter. This is ideal as you can catch errors before sending any data.
If however you have the need to stream your JSON response (ie: dealing with massive objects), you can set the StreamingJSON option to true. This will use the json.Encoder to stream the output to the http.ResponseWriter. If an error occurs, you will receive the error in your code, but the response will have already been sent. Also note that streaming is only implemented in render.JSON and not render.JSONP, and the UnEscapeHTML and Indent options are ignored when streaming.
However, encoding/json already buffers the complete output internally to catch errors, so this information is false.
I still think there are some benefits to the current approach (eg UnEscapeHTML
and Indent
) but I'd say that at the very least, the README should be updated to properly reflect the stdlib's behavior.
Here's some code to confirm:
package main
import (
"encoding/json"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", forcedErrorHandler)
http.ListenAndServe(":3000", nil)
}
func forcedErrorHandler(w http.ResponseWriter, r *http.Request) {
// attempting to encode a channel will fail.
if err := json.NewEncoder(w).Encode(make(chan int)); err != nil {
log.Printf("Errored: %v", err)
// json.NewEncoder hasn't written anything to the responsewriter at this point.
// we have full control over the writer here.
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error: " + err.Error()))
}
}
Cheers!
Thanks for pointing this out!!