Frage

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?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top