如何在Go语言中“桥接”写入者(writer)和读取者(reader)

huangapple go评论81阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2016年2月7日 22:11:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/35254527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定