Golang Code

Create Zip Files in Go

· 268 words · 2 minutes read #archive #compression #create #deflate #file #files #os #writer #zip #zipping

The code below shows how you can create a zip archive after being passed a number of files to compress. This is useful for both bundling files together and creating smaller file sizes.

The basics of it are to create the initial zip file then cycle through each file and add it to the archive using a zip writer, being sure to specify the deflate method to get better compression.

Also, try this code if you are unzipping files.

Initially based on this code. There’s also the docs for archive/zip.

package main

import (
    "archive/zip"
    "fmt"
    "io"
    "log"
    "os"
)

func main() {

    // Files to Zip
    files := []string{"example.csv", "data.csv"}
    output := "done.zip"

    err := ZipFiles(output, files)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Zipped File: " + output)
}

// ZipFiles compresses one or many files into a single zip archive file
func ZipFiles(filename string, files []string) error {

    newfile, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer newfile.Close()

    zipWriter := zip.NewWriter(newfile)
    defer zipWriter.Close()

    // Add files to zip
    for _, file := range files {

        zipfile, err := os.Open(file)
        if err != nil {
            return err
        }
        defer zipfile.Close()

        // Get the file information
        info, err := zipfile.Stat()
        if err != nil {
            return err
        }

        header, err := zip.FileInfoHeader(info)
        if err != nil {
            return err
        }

        // Change to deflate to gain better compression
        // see http://golang.org/pkg/archive/zip/#pkg-constants
        header.Method = zip.Deflate

        writer, err := zipWriter.CreateHeader(header)
        if err != nil {
            return err
        }
        _, err = io.Copy(writer, zipfile)
        if err != nil {
            return err
        }
    }
    return nil
}

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!