github.com/tickstep/library-go@v0.1.1/archive/archive.go (about)

     1  package archive
     2  
     3  import (
     4  	"compress/gzip"
     5  	"io"
     6  	"os"
     7  )
     8  
     9  // GZIPCompress GZIP 压缩
    10  func GZIPCompress(src io.Reader, writeTo io.Writer) (err error) {
    11  	w := gzip.NewWriter(writeTo)
    12  	_, err = io.Copy(w, src)
    13  	if err != nil {
    14  		return
    15  	}
    16  
    17  	w.Flush()
    18  	return w.Close()
    19  }
    20  
    21  // GZIPUncompress GZIP 解压缩
    22  func GZIPUncompress(src io.Reader, writeTo io.Writer) (err error) {
    23  	unReader, err := gzip.NewReader(src)
    24  	if err != nil {
    25  		return err
    26  	}
    27  
    28  	_, err = io.Copy(writeTo, unReader)
    29  	if err != nil {
    30  		return
    31  	}
    32  
    33  	return unReader.Close()
    34  }
    35  
    36  // GZIPCompressFile GZIP 压缩文件
    37  func GZIPCompressFile(filePath string) (err error) {
    38  	return gzipCompressFile("en", filePath)
    39  }
    40  
    41  // GZIPUnompressFile GZIP 解压缩文件
    42  func GZIPUnompressFile(filePath string) (err error) {
    43  	return gzipCompressFile("de", filePath)
    44  }
    45  
    46  func gzipCompressFile(op, filePath string) (err error) {
    47  	f, err := os.Open(filePath)
    48  	if err != nil {
    49  		return
    50  	}
    51  
    52  	fInfo, err := f.Stat()
    53  	if err != nil {
    54  		return
    55  	}
    56  
    57  	tempFilePath := filePath + ".gzip.tmp"
    58  	// 保留文件权限
    59  	tempFile, err := os.OpenFile(tempFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fInfo.Mode())
    60  	if err != nil {
    61  		return
    62  	}
    63  
    64  	switch op {
    65  	case "en":
    66  		err = GZIPCompress(f, tempFile)
    67  	case "de":
    68  		err = GZIPUncompress(f, tempFile)
    69  	default:
    70  		panic("unknown op" + op)
    71  	}
    72  	tempFile.Close()
    73  	f.Close()
    74  
    75  	if err != nil {
    76  		os.Remove(tempFilePath)
    77  		return
    78  	}
    79  
    80  	return os.Rename(tempFilePath, filePath)
    81  }