fstab
fstab

Reputation: 5029

can I obtain a io.Writer from a http.ResponseWriter?

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?

Upvotes: 2

Views: 2900

Answers (1)

Sebastian
Sebastian

Reputation: 17433

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.

Upvotes: 8

Related Questions