Home  >  Article  >  Backend Development  >  How to Unzip Password-Protected Zip Files in Golang?

How to Unzip Password-Protected Zip Files in Golang?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 01:48:29667browse

How to Unzip Password-Protected Zip Files in Golang?

Unzipping Password-Protected Zip Files in Golang

The recent release of Golang 1.2 introduced the archive/zip package. However, it appears to offer basic zip functionality and lacks support for unzipping password-protected zip files. To address this, an alternative approach is to utilize 7zip.

Solution: Using 7zip via Go's os/exec Package

Given that 7zip provides robust zip functionality, including password-protected unzipping, we can leverage Go's os/exec package to execute 7zip commands from within our Go code.

Code Example

The following Go code demonstrates how to extract a password-protected zip file using 7zip:

<code class="go">import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    zipPath := "path/to/password-protected.zip"
    extractPath := "path/to/extract/to"
    password := "secret"

    // Construct the 7zip command string
    commandString := fmt.Sprintf(`7za e %s -o%s -p"%s" -aoa`, zipPath, extractPath, password)
    commandSlice := strings.Fields(commandString)

    // Execute the 7zip command
    c := exec.Command(commandSlice[0], commandSlice[1:]...)
    err := c.Run()
    if err != nil {
        panic(err)
    }

    fmt.Printf("Unzipped password-protected zip file to %s\n", extractPath)
}</code>

Usage

  • Ensure that 7zip is installed and accessible on your system.
  • Adjust the zipPath and extractPath variables to the actual locations of the password-protected zip file and the desired extraction directory, respectively.
  • Run the Go program to perform the password-protected zip extraction.

This solution effectively utilizes 7zip's proven zip functionality, providing a straightforward way for Golang developers to handle password-protected zip files.

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

Statement:
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