Reputation: 2453
I usually find my way with Reader and Writer in Golang but I came to a situation new to me.
I am using "golang.org/x/net/html" Render. It outputs to a Writer w. I want to use that output and create a new request from that. NewRequest uses a Reader r.
err := html.Render(w, msg)
...
req, err := http.NewRequest("Post", url, r)
io.Copy(w, r)
My question is "what is the best/ideomatic solution for binding the two calls using w and r?". I could not find an example for a similar situation on the web. I am thinking about creating both Reader and Writer and using io.Copy(w, r) on them. I am not sure since this appears a little complicated for something that apparently is used often.
Upvotes: 2
Views: 3256
Reputation: 120941
A simple approach is to use a bytes.Buffer:
var buf bytes.Buffer
err := html.Render(&buf, msg)
...
req, err := http.NewRequest("POST", url, &buf)
This buffers the entire request in memory. An alternate approach that does not buffer everything in memory is to use io.Pipe. This approach is more complicated because it introduces concurrency in the program. Also, the http client starts to write the request to the wire before possible errors are detected in Render.
r, w := io.Pipe()
go func() {
w.CloseWithError(html.Render(w, msg))
}()
req, err := http.NewRequest("POST", url, r)
Upvotes: 7