To extract files from a zip archive in Go, you can make use of the archive/zip
package provided by the standard library. Here's an example of how you can do it:
package main
import (
"archive/zip"
"fmt"
"io"
"log"
"os"
"path/filepath"
)
func main() {
// Open the zip file
zipFile, err := zip.OpenReader("path/to/archive.zip")
if err != nil {
log.Fatal(err)
}
defer zipFile.Close()
// Create a directory for extracted files
extractDir := "path/to/extract"
os.MkdirAll(extractDir, os.ModePerm)
// Extract each file from the zip archive
for _, file := range zipFile.File {
destPath := filepath.Join(extractDir, file.Name)
// If the file is a directory, create it
if file.FileInfo().IsDir() {
os.MkdirAll(destPath, os.ModePerm)
continue
}
// Open the source file inside the zip
srcFile, err := file.Open()
if err != nil {
log.Fatal(err)
}
defer srcFile.Close()
// Create the destination file
destFile, err := os.OpenFile(
destPath,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
file.Mode(),
)
if err != nil {
log.Fatal(err)
}
defer destFile.Close()
// Copy the contents of the source file to destination file
_, err = io.Copy(destFile, srcFile)
if err != nil {
log.Fatal(err)
}
// Optionally, you can print the extracted file name
fmt.Println("Extracted:", file.Name)
}
fmt.Println("Extraction completed.")
}
Make sure to replace "path/to/archive.zip"
with the actual path to your zip archive file. Also, change "path/to/extract"
to the desired directory where you want to extract the files.
This code will open the zip file, create a directory for the extracted files, and then extract each file from the archive one by one. If a file inside the archive has a directory structure, it will be created before extracting the file. Finally, it will print the names of the extracted files.