1package archiver 2 3import ( 4 "compress/gzip" 5 "fmt" 6 "io" 7 "path/filepath" 8) 9 10// Gz facilitates gzip compression. 11type Gz struct { 12 CompressionLevel int 13} 14 15// Compress reads in, compresses it, and writes it to out. 16func (gz *Gz) Compress(in io.Reader, out io.Writer) error { 17 w, err := gzip.NewWriterLevel(out, gz.CompressionLevel) 18 if err != nil { 19 return err 20 } 21 defer w.Close() 22 _, err = io.Copy(w, in) 23 return err 24} 25 26// Decompress reads in, decompresses it, and writes it to out. 27func (gz *Gz) Decompress(in io.Reader, out io.Writer) error { 28 r, err := gzip.NewReader(in) 29 if err != nil { 30 return err 31 } 32 defer r.Close() 33 _, err = io.Copy(out, r) 34 return err 35} 36 37// CheckExt ensures the file extension matches the format. 38func (gz *Gz) CheckExt(filename string) error { 39 if filepath.Ext(filename) != ".gz" { 40 return fmt.Errorf("filename must have a .gz extension") 41 } 42 return nil 43} 44 45func (gz *Gz) String() string { return "gz" } 46 47// NewGz returns a new, default instance ready to be customized and used. 48func NewGz() *Gz { 49 return &Gz{ 50 CompressionLevel: gzip.DefaultCompression, 51 } 52} 53 54// Compile-time checks to ensure type implements desired interfaces. 55var ( 56 _ = Compressor(new(Gz)) 57 _ = Decompressor(new(Gz)) 58) 59 60// DefaultGz is a default instance that is conveniently ready to use. 61var DefaultGz = NewGz() 62