我在磁盤上有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 回答
- 0 關注
- 162 瀏覽
添加回答
舉報
0/150
提交
取消