Golang version 1.23.6 supporting tar and zip compressing. In this article I will show you how to compress directory with Golang
Creating a output file
First we need to create output file.
filename := "test.zip" output_file, err := os.Create(filename) if err != nil { panic(err) }
if you want to compress with tar file, you can replace extension to the .tar
Creating a writer
w := zip.NewWriter(output_file) defer w.Close()
creating new file under the zip stream
path := "helloworld.txt" zipFile, err := w.Create(path) if err != nil { panic(err) }
Writing to the zip stream
myBytes := []byte("hello world !") zipFile.Write(myBytes)
let's see output
> unzip -l test.zip
Length Date Time Name --------- ---------- ----- ---- 13 00-00-1980 00:00 helloworld.txt --------- ------- 13 1 file
> zipinfo test.zip Archive: test.zip Zip file size: 161 bytes, number of entries: 1 -rw---- 2.0 fat 13 bl defN 80-000-00 00:00 helloworld.txt 1 file, 13 bytes uncompressed, 19 bytes compressed: -46.2%
> unzip -p test.zip helloworld.txt hello world !%
Writing header metadata
CreateHeader method provides creating new zip file with metadata in stream
zipFile, err := w.CreateHeader(&zip.FileHeader{ Name: path, Comment: "Test Comment", Modified: time.Now()}, )
let's check out again the zip file :
> zipinfo test.zip Archive: test.zip Zip file size: 185 bytes, number of entries: 1 -rw---- 2.0 fat 13 bX stor 25-Feb-07 14:35 helloworld.txt 1 file, 13 bytes uncompressed, 13 bytes compressed: 0.0%
we can see that file modification date is updated
Message length should be less than 1024 character!