亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

確定Golang Gzip文件的長度而不讀取它?

確定Golang Gzip文件的長度而不讀取它?

Go
紅顏莎娜 2022-08-15 19:48:00
我在磁盤上有gzi壓縮的文件,我希望將其流式傳輸到未壓縮的HTTP客戶端。為此,我需要發送一個長度標頭,然后將未壓縮的文件流式傳輸到客戶端。我知道gzip協議存儲了未壓縮數據的原始長度,但據我所知,golang的“compress/gzip”包似乎沒有辦法抓住這個長度。我已經訴諸于將文件讀入變量,然后從中獲取字符串長度,但這非常低效并且浪費內存,尤其是在較大的文件上。Bellow 我已經發布了我最終使用的代碼: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 headersw.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 headersw.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壓縮文件的未壓縮長度?
查看完整描述

1 回答

?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

gzip 格式可能看起來提供了未壓縮的長度,但實際上它并沒有。不幸的是,獲得未壓縮長度的唯一可靠方法是解壓縮gzip流。(您可以只計算字節數,而不將未壓縮的數據保存在任何地方。

請參閱此答案以了解原因。


查看完整回答
反對 回復 2022-08-15
  • 1 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號