Mastering TAR Archives in Go: Create and Extract Files with archive/tar
This guide explains how to use Go's archive/tar package to create and extract TAR archives, covering the package overview, key types like Writer, Reader, and Header, and providing complete code examples and UML diagrams to illustrate the process.
Introduction
The Go standard library includes the archive/tar package, which implements reading and writing of TAR archives – a simple concatenation format widely used on Unix/Linux systems for bundling multiple files.
Package Overview
Key types provided by archive/tar: Writer: writes a sequence of Header and file data to an io.Writer. Reader: reads a TAR stream from an io.Reader, exposing each file via Header. Header: describes a single entry (name, size, mode, timestamps, type flag, etc.).
Typical fields of Header include Name, Size, Mode (file permissions as an octal os.FileMode), ModTime, Typeflag (e.g., tar.TypeReg for regular files), and optional UID/GID.
Creating a TAR File
Use tar.NewWriter with any io.Writer (e.g., an os.File). The example below creates a plain TAR archive; wrapping the writer with gzip.NewWriter would produce a .tar.gz file.
package main
import (
"archive/tar"
"os"
)
func main() {
// Open the output file.
outFile, err := os.Create("example.tar")
if err != nil {
panic(err)
}
defer outFile.Close()
// Create a tar.Writer.
tw := tar.NewWriter(outFile)
defer tw.Close() // Flushes the end‑of‑archive block.
// Define files to add.
files := []struct {
Name string
Body string
}{
{"readme.txt", "This archive contains some text files."},
{"gopher.txt", "Gopher names:
George
Geoffrey
Gonzo"},
{"todo.txt", "Get animal handling licence.
Write more examples."},
}
for _, f := range files {
hdr := &tar.Header{
Name: f.Name,
Mode: 0600, // octal file permission
Size: int64(len(f.Body)), // size in bytes
// Typeflag defaults to tar.TypeReg (regular file).
}
if err := tw.WriteHeader(hdr); err != nil {
panic(err)
}
if _, err := tw.Write([]byte(f.Body)); err != nil {
panic(err)
}
}
}Extracting a TAR File
Reading follows the same pattern: create a tar.Reader from an io.Reader, then repeatedly call Next() until it returns io.EOF. Each call yields a populated Header and positions the reader at the file's data.
package main
import (
"archive/tar"
"fmt"
"io"
"os"
)
func main() {
// Open the TAR archive for reading.
inFile, err := os.Open("example.tar")
if err != nil {
panic(err)
}
defer inFile.Close()
tr := tar.NewReader(inFile)
for {
hdr, err := tr.Next()
if err == io.EOF {
break // No more entries.
}
if err != nil {
panic(err)
}
fmt.Printf("Contents of %s:
", hdr.Name)
// Copy the file's data to stdout (or any other destination).
if _, err := io.Copy(os.Stdout, tr); err != nil {
panic(err)
}
fmt.Println()
}
}UML Diagram of the Process
The following PlantUML diagram visualises the creation and extraction workflow.
Conclusion
The archive/tar package provides a straightforward API for creating and extracting TAR archives. By leveraging tar.Writer and tar.Reader, Go programs can bundle multiple files, preserve metadata, and integrate with compression layers (e.g., gzip) for efficient backup or distribution workflows.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
