英文:
how to "bridge" writer and reader in go
问题
我通常使用Golang中的Reader和Writer来找到我的方法,但我遇到了一个对我来说新的情况。
我正在使用"golang.org/x/net/html"的Render函数。它将输出到一个Writer w。我想使用该输出创建一个新的请求。NewRequest函数使用一个Reader r。
err := html.Render(w, msg)
...
req, err := http.NewRequest("Post", url, r)
io.Copy(w, r)
我的问题是,“如何使用w和r绑定这两个调用的最佳/惯用解决方案是什么?”我在网上找不到类似情况的示例。我正在考虑创建一个Reader和一个Writer,并在它们上使用io.Copy(w, r)。但我不确定,因为这似乎对于经常使用的东西来说有点复杂。
英文:
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.
答案1
得分: 5
一个简单的方法是使用bytes.Buffer
:
var buf bytes.Buffer
err := html.Render(&buf, msg)
...
req, err := http.NewRequest("POST", url, &buf)
这将在内存中缓冲整个请求。另一种不将所有内容都缓冲在内存中的方法是使用io.Pipe
。这种方法更加复杂,因为它在程序中引入了并发。此外,在Render中检测到可能的错误之前,http客户端开始将请求写入网络。
r, w := io.Pipe()
go func() {
w.CloseWithError(html.Render(w, msg))
}()
req, err := http.NewRequest("POST", url, r)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论