Writing archive tar files using GoLang; adding compression using Gzip

Kassim Damilola
Nov 6 · 2 min read

Tar in itself just bundles files together. Usually you use gzip along with tar to compress the resulting tarball, thus achieving similar results as with zip.

Go makes taring and un-taring files very easy with the archive\tar standard libraries. This post shows how to use the archive and the compress packages to create code that can programmatically build or extract compressed files from tar-encoded archive files.

Archive-tar directory with GoLang

package main
import (
"archive/tar"
"io"
"os"
"path/filepath"
)
// The tarF function takes in two argument, one is the intended .tar // target output and the director we want to archive
func tarF (target, tDirectory string){
}

> Check if the directory to tar exist

dir, err := os.Open(tDirectory)
if err != nil {
os.Exit(1)
}
defer dir.Close()
// list the files in the directory
files, err := dir.Readdir(0)
if err != nil {
os.Exit(1)
}

> Create tar file and prepare to write

tarfile, err := os.Create(target)
if err != nil {
os.Exit(1)
}
defer tarfile.Close()
var fileW io.WriteCloser = tarfile//Tar file writter
tarfileW := tar.NewWriter(fileW)
defer tarfileW.Close()

> Write each file in the directory into the new tar directory

for _, fileInfo := range files {
if fileInfo.IsDir() {
continue
}
file, err := os.Open(dir.Name() + string(filepath.Separator) + fileInfo.Name())
if err != nil {
os.Exit(1)
}
defer file.Close() header := new(tar.Header)
header.Name = file.Name()
header.Size = fileInfo.Size()
header.Mode = int64(fileInfo.Mode())
header.ModTime = fileInfo.ModTime()
err = tarfileW.WriteHeader(header)
if err != nil {
os.Exit(1)
}
_, err = io.Copy(tarfileW, file)
if err != nil {
os.Exit(1)
}
}

> Trying the function

func main() {
tarF("./finance.tar", "../finance")
}

If all goes well, running the code would create a finance.tar in the specified file directory.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade