To create a zip archive from files and directories in Go, you can use the archive/zip
package.
Here's an example program that creates a zip archive from a list of files and directories:
package main
import (
"archive/zip"
"io"
"log"
"os"
"path/filepath"
)
func main() {
// Create a new zip archive file named "archive.zip"
zipfile, err := os.Create("archive.zip")
if err != nil {
log.Fatal(err)
}
defer zipfile.Close()
// Create a new zip writer
zipWriter := zip.NewWriter(zipfile)
defer zipWriter.Close()
// List of files and directories to add to the zip archive
files := []string{"file.txt", "dir"}
for _, file := range files {
err := addFileToZip(zipWriter, file)
if err != nil {
log.Fatal(err)
}
}
log.Println("Zip archive created successfully")
}
func addFileToZip(zipWriter *zip.Writer, file string) error {
// Open the file for reading
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
// Get file info
info, err := f.Stat()
if err != nil {
return err
}
// If the file is a directory, create a new directory header in the zip archive
if info.IsDir() {
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = file + "/"
header.Method = zip.Deflate
_, err = zipWriter.CreateHeader(header)
if err != nil {
return err
}
} else {
// If the file is a regular file, create a new file header in the zip archive
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Method = zip.Deflate
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
// Copy the file contents to the zip writer
_, err = io.Copy(writer, f)
if err != nil {
return err
}
}
return nil
}
In this example, we create a zip archive file named "archive.zip". We then iterate over a list of files and directories (files
) and use the addFileToZip
function to add each entry to the zip archive.
The addFileToZip
function takes a zip writer, opens the file or directory, and adds it to the zip archive. If the entry is a directory, a new directory header is created in the zip archive. If the entry is a regular file, a new file header is created and the file contents are copied to the zip writer.