go 文件流转发

       先读入内存再返回的方式,不仅耗时,而且会占用较大的内存;

       直接通过文件流方式,读一点,返回给前端一点,这样的方式更高效。

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值