先读入内存再返回的方式,不仅耗时,而且会占用较大的内存;
直接通过文件流方式,读一点,返回给前端一点,这样的方式更高效。
package test
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"testing"
)
func TestServer(t *testing.T) {
http.HandleFunc("/download/remote/stream", downloadRemoteWithStream)
http.HandleFunc("/download/remote/bytes", downloadRemoteWithBytes)
http.HandleFunc("/download/local/stream", downloadLocalWithStream)
http.HandleFunc("/download/local/bytes", downloadLocalWithBytes)
http.ListenAndServe(":8080", nil)
}
// downloadRemoteWithStream 转发流,高效
func downloadRemoteWithStream(w http.ResponseWriter, r *http.Request) {
resp, err := http.Get("http//ip:port/path/filename")
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusBadRequest)
return
}
fmt.Println("result:", resp.Body)
w.Header().Add("Content-Type", "binary/octet-stream")
w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", "file.csv"))
io.Copy(w, resp.Body)
//br := bufio.NewReader(result.Body)
//br.WriteTo(w)
}
// downloadRemoteWithBytes 先全部下载读入内存,再返回给前端,低效
func downloadRemoteWithBytes(w http.ResponseWriter, r *http.Request) {
resp, err := http.Get("http//ip:port/path/filename")
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusNotFound)
return
}
fmt.Println("result:", resp.Body)
w.Header().Add("Content-Type", "binary/octet-stream")
w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", "file.csv"))
contentBytes, err := ioutil.ReadAll(resp.Body)
w.Write(contentBytes)
}
// downloadLocalWithStream 文件流方式下载本地文件,高效
func downloadLocalWithStream(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("/path/filename")
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Add("Content-Type", "binary/octet-stream")
w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", "file.csv"))
io.Copy(w, file)
//reader := bufio.NewReader(file)
//reader.WriteTo(w)
}
// downloadLocalWithBytes 先将文件内容完全读入内存,再一次性返回给前端,低效
func downloadLocalWithBytes(w http.ResponseWriter, r *http.Request) {
file, err := os.Open("/path/filename")
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Add("Content-Type", "binary/octet-stream")
w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", "file.csv"))
contentBytes, _ := ioutil.ReadAll(file)
w.Write(contentBytes)
}