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.

On Sat, Oct 1, 2016 at 8:51 PM Lax Clarke <lax.cla...@gmail.com> wrote:

> 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
> (see: https://golang.org/pkg/encoding/json/#NewEncoder)
>
> While, http.NewRequest accepts an io.Reader as the body of request.
> (see: https://golang.org/pkg/net/http/#NewRequest)
>
> So, what's the best way to take a golang struct and marshal it as a JSON
> body of an http request?
>
> Thanks.
>
> --
> 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+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to