我在磁盘上有 gzip 压缩文件,我希望将其以未压缩的方式流式传输到 HTTP 客户端。为此,我需要发送一个长度标头,然后将未压缩的文件流式传输到客户端。我知道 gzip 协议存储未压缩数据的原始长度,但据我所知,golang 的“compress/gzip”包似乎没有办法获取这个长度。我已经采取将文件读入变量,然后从中获取字符串长度的方法,但这非常低效并且浪费内存,尤其是在较大的文件上。
下面我发布了我最终使用的代码:
DownloadHandler(w http.ResponseWriter, r *http.Request) {
path := "/path/to/thefile.gz";
openfile, err := os.Open(path);
if err != nil {
w.WriteHeader(http.StatusNotFound);
fmt.Fprint(w, "404");
return;
}
defer openfile.Close();
fz, err := gzip.NewReader(openfile);
if err != nil {
w.WriteHeader(http.StatusNotFound);
fmt.Fprint(w, "404");
return;
}
defer fz.Close()
// Wastefully read data into a string so I can get the length.
s, err := ioutil.ReadAll(fz);
r := strings.NewReader(string(s));
//Send the headers
w.Header().Set("Content-Disposition", "attachment; filename=test");
w.Header().Set("Content-Length", strconv.Itoa(len(s))); // Send length to client.
w.Header().Set("Content-Type", "text/csv");
io.Copy(w, r) //'Copy' the file to the client
}
Run Code Online (Sandbox Code Playgroud)
我期望能够做的是这样的:
DownloadHandler(w http.ResponseWriter, r *http.Request) {
path := "/path/to/thefile.gz";
openfile, err := os.Open(path);
if err != nil {
w.WriteHeader(http.StatusNotFound);
fmt.Fprint(w, "404");
return;
}
defer openfile.Close();
fz, err := gzip.NewReader(openfile);
if err != nil {
w.WriteHeader(http.StatusNotFound);
fmt.Fprint(w, "404");
return;
}
defer fz.Close()
//Send the headers
w.Header().Set("Content-Disposition", "attachment; filename=test");
w.Header().Set("Content-Length", strconv.Itoa(fz.Length())); // Send length to client.
w.Header().Set("Content-Type", "text/csv");
io.Copy(w, fz) //'Copy' the file to the client
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何在 golang 中获取 gzip 压缩文件的未压缩长度?