登录
首页 >  Golang >  Go问答

在不读取 Golang Gzip 文件的情况下确定其长度?

来源:stackoverflow

时间:2024-04-05 22:42:35 382浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《在不读取 Golang Gzip 文件的情况下确定其长度?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我在磁盘上有 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
}

我希望能够做的是这样的:

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
}

有人知道如何在 golang 中获取 gzip 压缩文件的未压缩长度吗?


解决方案


gzip 格式可能看起来提供未压缩的长度,但实际上并没有。不幸的是,获得未压缩长度的唯一可靠方法是解压缩 gzip 流。 (您可以只计算字节数,而不将未压缩的数据保存在任何地方。)

请参阅 this answer 了解原因。

到这里,我们也就讲完了《在不读取 Golang Gzip 文件的情况下确定其长度?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>