How to Unzip Password-Protected ZIP Files in Go?

Mary-Kate Olsen
Release: 2024-10-31 16:32:01
Original
526 people have browsed it

How to Unzip Password-Protected ZIP Files in Go?

Unzipping Password-Protected ZIP Files in Go 1.2

In Go 1.2, the archive/zip package provides basic zip functionality, but lacks support for handling password-protected files. To unzip such files, it is recommended to utilize the os/exec package in conjunction with external tools like 7zip.

Using 7zip to Extract Password-Protected ZIP Files

The following example demonstrates how to extract a password-protected ZIP file using 7zip:

<code class="go">func extractZipWithPassword() {
    fmt.Printf("Unzipping `%s` to directory `%s`\n", zip_path, extract_path)
    commandString := fmt.Sprintf(`7za e %s -o%s -p"%s" -aoa`, zip_path, extract_path, zip_password)
    commandSlice := strings.Fields(commandString)
    fmt.Println(commandString)
    c := exec.Command(commandSlice[0], commandSlice[1:]...)
    e := c.Run()
    checkError(e)
}</code>
Copy after login

In this example, we construct a command string using the 7za executable to extract the ZIP file. We specify the file path, extraction directory, password, and additional options to overwrite existing files and update archive timestamps (-aoa). Then, we execute the command using the exec.Command function and check for any errors.

Additional Resources

  • [7-Zip Official Website](https://www.7-zip.org/)
  • [7-Zip User Guide](https://wiki.7-zip.org/7-Zip_User_Guide)
  • [Go os/exec Package Documentation](https://golang.org/pkg/os/exec/)

Note:

While this approach relies on an external tool, it provides a straightforward solution for handling password-protected ZIP files in Go.

The above is the detailed content of How to Unzip Password-Protected ZIP Files in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!