Question

I would like to use json.Encoder to write to a http.ResponseWriter.

I wonder, where do I get http.ResponseWriter's own io.Writer ?

(io.Writer is required as parameter for json.NewEncoder)

any ideas?

Was it helpful?

Solution

http.ResponseWriter implements Write([]byte) (int, error). Therefore you can use it everywhere where a io.Writer is required.

func handler(w http.ResponseWriter, r *http.Request) {
    encoder := json.NewEncoder(w)
}

Here you can find some background information on how Go uses interfaces as a way to specify the behavior of an object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top