每当我使用 Go 从我的网站进行大量下载时,它会阻止我在下载的同时在同一浏览器中在我的网站上导航或执行任何其他操作。这发生在 Firefox、chrome 和 Safari 上,这让我认为这是一个 conf 问题。去环境GO111MODULE=""GOARCH="amd64"GOBIN=""GOCACHE="/root/.cache/go-build"GOENV="/root/.config/go/env"GOEXE=""GOFLAGS=""GOHOSTARCH="amd64"GOHOSTOS="linux"GOINSECURE=""GONOPROXY=""GONOSUMDB=""GOOS="linux"GOPATH="/home/go"GOPRIVATE=""GOPROXY="https://proxy.golang.org,direct"GOROOT="/usr/local/go"GOSUMDB="sum.golang.org"GOTMPDIR=""GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"GCCGO="gccgo"AR="ar"CC="gcc"CXX="g++"CGO_ENABLED="1"GOMOD=""CGO_CFLAGS="-g -O2"CGO_CPPFLAGS=""CGO_CXXFLAGS="-g -O2"CGO_FFLAGS="-g -O2"CGO_LDFLAGS="-g -O2"PKG_CONFIG="pkg-config"GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build062753082=/tmp/go-build"为此使用默认的 GO Web 服务器 net/http。编辑:抱歉忘记了下载代码func FunctionName(res http.ResponseWriter, req *http.Request, p httprouter.Params) { defer req.Body.Close() setSecurityHeaders(res) req.ParseForm() id := p.ByName("id") incletter, err := GetIncLetterById(bson.ObjectIdHex(id)) if err != nil { jsonResponse(res, map[string]string{"status": "error", "message": "."}) return } bytes, filename := incletter.GetFileBytes() res.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"") res.Header().Set("Content-type", "application/pdf") res.Header().Set("Content-Length", strconv.Itoa(len(bytes))) res.Write(bytes)}
2 回答

一只甜甜圈
TA贡献1836条经验 获得超5个赞
您的标头看起来不错(尽管我认为正确的内容类型表示法是正确的大小写(“ Content-Type”)。如果这只发生在大文件中,我怀疑这意味着整个文件在流式传输到客户端之前被加载到内存中。解决这个问题,您可以使用以下内容:
byteSlice, filename := incletter.GetFileBytes()
byteStream := bytes.NewReader(byteSlice)
res.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
res.Header().Set("Content-type", "application/pdf")
res.Header().Set("Content-Length", strconv.Itoa(len(bytes)))
io.Copy(res, byteStream)
这将实质上从读取器接口流向写入器,直接流向客户端。
- 2 回答
- 0 关注
- 129 浏览
添加回答
举报
0/150
提交
取消