Use the archive/zip package to create a Writer for writing and a Reader for reading ZIP archives. The following example demonstrates how to write a file to a ZIP archive and then read it back.
package main
import (
"archive/zip"
"fmt"
"io"
"os"
)
func main() {
// Write a ZIP file
file, _ := os.Create("example.zip")
defer file.Close()
w := zip.NewWriter(file)
defer w.Close()
f, _ := w.Create("hello.txt")
f.Write([]byte("Hello, World!"))
// Read the ZIP file
reader, _ := zip.OpenReader("example.zip")
defer reader.Close()
for _, f := range reader.File {
if f.FileInfo().IsDir() {
continue
}
rc, _ := f.Open()
data, _ := io.ReadAll(rc)
fmt.Printf("%s: %s\n", f.Name, string(data))
rc.Close()
}
}