douguazhi5966 2016-02-07 14:11
浏览 21
已采纳

如何“桥接”作者和读者

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条回答 默认 最新

  • duanjiushu5063 2016-02-07 14:19
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计