如何将 io.ReadCloser 流式传输到 http.ResponseWriter

How to stream an io.ReadCloser into a http.ResponseWriter

我有一个请求下载文件的客户端,Web 服务器将此请求转发到实际保存该文件的资源服务器。从资源服务器返回的 *http.Response 具有主体 io.ReaderCloser 从资源服务器流式传输文件内容。但是我正处于我想开始将其写入来自客户的原始 http.ResponseWriter 的地步。查看 http.ResponseWriter 接口,它只包含一个采用字节片段的 Write 方法,这让我认为将文件内容返回给客户端的唯一方法是读取 Body io.ReaderCloser放入缓冲区,然后将其放入 http.ResponseWriter 的 Write 方法。我不想这样做,因为那是非常低效的,通过我的网络服务器流式传输它会更好。这可能吗?

这里有一些代码来说明:

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 ?
})

您可以使用 io.Copy() 来完成此操作。

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

还要注意 Copy() 不会 return io.EOF 而是 nil 因为如果它可以 "copy" 一切直到 src 报告 io.EOF,这不算错误。