How to Tar and Un-tar files in Golang

Image by seraffil

Go makes taring and un-taring files very easy with the following standard libraries:

“archive/tar”
“compress/gzip"

Taring files in Golang

A source is passed into Tar, along with multiple io.Writer’s. After ensuring the source exists, it is walked recursively, creating a tar header for all files and directories, however only files are opened and their contents copied over.

Important

You may need to modify the header.Name in a way that will get the desired file structure when un-tarring (as I’ve done here).

If during the tarring process, headers are not added for directories, the un-tarring process wont work quite right. The idea here is that the tarring process should function the same as an OS’s tar method so that these files can be un-tarred correctly.

Un-taring files in Golang

The example here creates a tar.Reader and then fires up a for loop.

The first thing the loop does is advance the archive by getting the next header (exiting the loop on io.EOF). Each header is checked to see if it is for a file or a directory by switching on the header.Typeflag.

If it’s a tar.TypeDir, and it doesn’t already exist, it is created with os.MkdirAll().

If it’s tar.TypeReg, the file is created (ensuring to give it the same file permissions it had when tarred), and then the contends of the archive are copied into the new file, then rinse-and-repeat…

Easy!