github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/utils/bdcrypto/archive.go (about) 1 package bdcrypto 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 defer f.Close() 53 54 fInfo, err := f.Stat() 55 if err != nil { 56 return 57 } 58 59 tempFilePath := filePath + ".gzip.tmp" 60 // 保留文件权限 61 tempFile, err := os.OpenFile(tempFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fInfo.Mode()) 62 if err != nil { 63 return 64 } 65 66 defer tempFile.Close() 67 68 switch op { 69 case "en": 70 err = GZIPCompress(f, tempFile) 71 case "de": 72 err = GZIPUncompress(f, tempFile) 73 default: 74 panic("unknown op" + op) 75 } 76 77 if err != nil { 78 os.Remove(tempFilePath) 79 return 80 } 81 82 return os.Rename(tempFilePath, filePath) 83 }