import ( "archive/zip" "fmt" "os" ) func main() { // open the zip file r, err := zip.OpenReader("myarchive.zip") if err != nil { fmt.Println(err) os.Exit(1) } defer r.Close() // print the names of all files in the archive for _, f := range r.File { fmt.Println(f.Name) } }
import ( "archive/zip" "fmt" "io" "os" ) func main() { // open the zip file r, err := zip.OpenReader("myarchive.zip") if err != nil { fmt.Println(err) os.Exit(1) } defer r.Close() // find the file we want to extract var targetFile *zip.File for _, f := range r.File { if f.Name == "target.txt" { targetFile = f break } } // extract the file contents to a new file if targetFile != nil { outFile, err := os.Create("target.txt") if err != nil { fmt.Println(err) os.Exit(1) } defer outFile.Close() rc, err := targetFile.Open() if err != nil { fmt.Println(err) os.Exit(1) } defer rc.Close() _, err = io.Copy(outFile, rc) if err != nil { fmt.Println(err) os.Exit(1) } } }In this example, we again use the `zip.OpenReader` function to open the zip archive. We look for a file named "target.txt" and extract its contents to a new file with the same name. To do this, we use the `zip.File.Open` method to get an `io.ReadCloser` for the file's contents, which we can then copy to the output file using `io.Copy`.