douliao1911 2016-01-18 12:56
浏览 851
已采纳

如何将io.ReadCloser流式传输到golang中的http.ResponseWriter?

I have a client which makes a request to download a file, the web server forwards this request on to the resource server that actually holds the file. The *http.Response back from the resource server has the Body io.ReaderCloser streaming the file contents from the resource server. But I'm then at the point where I want to start writing that into the original http.ResponseWriter that came from the client. Looking at the http.ResponseWriter interface it only contains a Write method which takes a slice of bytes, which makes me think that the only way to get the file contents back to the client is to read the Body io.ReaderCloser into a buffer and then put that into the http.ResponseWriter's Write method. which I dont want to do since that is hugely inefficient and it would be much better to stream it through my web server. Is this possible?

here is some code to illustrate:

getFile() *http.Response {
    //make a request to resource server and return the response object
}

// handle request from client
http.HandleFunc("/getFile", func(w http.ResponseWriter, r *http.Request){
    res := getFile()
    //how can I stream res.Body into w without buffering ?
})
  • 写回答

1条回答 默认 最新

  • dongyou2714 2016-01-18 12:59
    关注

    You can use io.Copy() which does exactly this.

    Copy copies from src to dst until either EOF is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any.

    n, err := io.Copy(w, res.Body)
    // check err
    

    Also note that Copy() will not return io.EOF but nil because if it can "copy" everything until src reports io.EOF, that is not considered an error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有卷积神经网络识别害虫的项目吗
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件