encode struct as JSON, and use it in http.NewRequest ( io.Writer vs. io.Reader issue )H

83 views
Skip to first unread message

Lax Clarke

unread,
Oct 1, 2016, 11:51:06 PM10/1/16
to golang-nuts
Hi,

I want to marshall a struct as JSON and use it in an http.NewRequest.
The problem is, encoding/json package provides NewEncoder, but that works on an io.Writer

While, http.NewRequest accepts an io.Reader as the body of request.

So, what's the best way to take a golang struct and marshal it as a JSON body of an http request?

Thanks.

Matt Harden

unread,
Oct 2, 2016, 12:03:46 AM10/2/16
to Lax Clarke, golang-nuts
You could use bytes.Buffer to encode it into a buffer beforehand and then pass that as the body, or you could use an io.Pipe which essentially connects a Reader to a Writer, which allows you to encode on the fly as the http client reads the body to send it along. However I think encoding/json may already buffer the whole contents of the JSON anyway so using io.Pipe might not help int that regard. It's probably simplest and clearest to use the Buffer.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Shawn Milochik

unread,
Oct 2, 2016, 12:13:33 AM10/2/16
to golang-nuts

Edward Muller

unread,
Oct 3, 2016, 2:55:38 PM10/3/16
to Sh...@milochik.com, golang-nuts

On Sat, Oct 1, 2016 at 9:13 PM Shawn Milochik <shawn...@gmail.com> wrote:

How about https://golang.org/pkg/bytes/#NewReader ?

Reply all
Reply to author
Forward
0 new messages