Golang: Working with Gzip and Tar

Gzip

Gzip is another file compression format
that was created to replace the compress program used in early unix system.
It is normally used to compress just single files. Compressed archives are
created by packaging collections of files into a single tar archive,
and then compressing that archive with gzip. The final .tar.gz or .tgz file is a tarball.

Compressing a file

Compressing operation is very simple to implement. The package exposes gzip.Writer struct
that compress any content provided via its Write function. You can specify some metadata
information about the compressed file by setting some properties of gzip.Header
struct which is embedded into gzip.Writer:

Decompressing a file

This operation is simple as its contrapart. But in this case we should use
gzip.Reader to read the compressed array of bytes. We can read the metadata information
such as compressed file name via gzip.Header struct (embedded in gzip.Reader)

Usage

Tar

Tar is an archive file for
distribution of hudge fileset. Known as tap archive it was developed to
write data to sequential io devices.

The tar contains multiple paramaeters, such as timestamp, ownership, file
permissions and directories.

If you want to create a tar package, you should use the following
code snippet walk through the directory hierarchy and write its content. Every
written header encodes metadata file information os.FileInfo.
Because os.FileInfo’s Name method returns only the base name of
the file it describes, it may be necessary to modify the Name field
of the returned header to provide the full path name of the file.

To unpack a tar you should use tar.Reader struct to read all headers. Every
header declares the begining of every directory and file in the tarball. By accessing
its FileInfo property you can recreate the files and the directories: