Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StreamingJSON does nothing / information in README is false #70

Closed
dannyvankooten opened this issue Aug 6, 2018 · 1 comment
Closed

Comments

@dannyvankooten
Copy link

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!

@unrolled
Copy link
Owner

unrolled commented Aug 7, 2018

Thanks for pointing this out!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants