package main import ( "archive/zip" "fmt" "os" ) func main() { file, err := os.Create("example.zip") if err != nil { fmt.Println(err) return } defer file.Close() archive := zip.NewWriter(file) defer archive.Close() // create a new file in the archive f, err := archive.Create("file.txt") if err != nil { fmt.Println(err) return } // add content to the file _, err = f.Write([]byte("Hello, World!")) if err != nil { fmt.Println(err) return } fmt.Println("Zip archive created successfully") }
package main import ( "archive/zip" "fmt" "os" ) func main() { file, err := os.Create("example.zip") if err != nil { fmt.Println(err) return } defer file.Close() archive := zip.NewWriter(file) defer archive.Close() // add multiple files to the archive files := []struct { Name, Body string }{ {"file1.txt", "File 1 contents"}, {"file2.txt", "File 2 contents"}, } for _, file := range files { f, err := archive.Create(file.Name) if err != nil { fmt.Println(err) return } _, err = f.Write([]byte(file.Body)) if err != nil { fmt.Println(err) return } } fmt.Println("Zip archive created successfully") }This example shows how to create a ZIP archive with multiple files. We define a slice of structs containing the name and contents of each file. Then we iterate over the slice and create and add each file to the archive using archive.Create() and f.Write(). Overall, the archive/zip package is a standard library package and provides functionality for working with ZIP archives.