How can I use the “compress/gzip” package to gzip a file?

前端 未结 5 1248
长情又很酷
长情又很酷 2020-12-13 18:48

I\'m new to Go, and can\'t figure out how to use the compress/gzip package to my advantage. Basically, I just want to write something to a file, gzip it and rea

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 19:10

    Here the func for unpack gzip file to destination file:

    func UnpackGzipFile(gzFilePath, dstFilePath string) (int64, error) {
        gzFile, err := os.Open(gzFilePath)
        if err != nil {
            return 0, fmt.Errorf("Failed to open file %s for unpack: %s", gzFilePath, err)
        }
        dstFile, err := os.OpenFile(dstFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
        if err != nil {
            return 0, fmt.Errorf("Failed to create destination file %s for unpack: %s", dstFilePath, err)
        }
    
        ioReader, ioWriter := io.Pipe()
    
        go func() { // goroutine leak is possible here
            gzReader, _ := gzip.NewReader(gzFile)
            // it is important to close the writer or reading from the other end of the
            // pipe or io.copy() will never finish
            defer func(){
                gzFile.Close()
                gzReader.Close()
                ioWriter.Close()
            }()
    
            io.Copy(ioWriter, gzReader)
        }()
    
        written, err := io.Copy(dstFile, ioReader)
        if err != nil {
            return 0, err // goroutine leak is possible here
        }
        ioReader.Close()
        dstFile.Close()
    
        return written, nil
    }
    

提交回复
热议问题