Bagaimanakah saya boleh menyahzip fail dalam Go dengan cekap dengan pengendalian ralat dan pertimbangan keselamatan yang betul?

Linda Hamilton
Lepaskan: 2024-11-13 13:01:02
asal
413 orang telah melayarinya

How can I efficiently unzip files in Go with proper error handling and security considerations?

Unzip Files Effortlessly with Go

Unzipping files in Go is a straightforward task with the right tools. The zip package in Go provides a convenient way to extract files from ZIP archives.

Current Code

The code snippet provided initializes a zip reader, iterates over the files in the archive, and extracts them to the designated destination. The nested defer statements can lead to issues, as noted by @Nick Craig-Wood.

Improved Solution

To address this issue, a closure is introduced to encapsulate the file extraction and writing logic. Additionally, error handling is added to the Close() calls for both the zip reader and the individual file readers:

func Unzip(src, dest string) error {
    r, err := zip.OpenReader(src)
    if err != nil {
        return err
    }
    defer func() {
        if err := r.Close(); err != nil {
            panic(err)
        }
    }()

    os.MkdirAll(dest, 0755)

    extractAndWriteFile := func(f *zip.File) error {
        rc, err := f.Open()
        if err != nil {
            return err
        }
        defer func() {
            if err := rc.Close(); err != nil {
                panic(err)
            }
        }()

        ... (Code for file extraction and writing goes here) ...

        return nil
    }

    for _, f := range r.File {
        err := extractAndWriteFile(f)
        if err != nil {
            return err
        }
    }

    return nil
}
Salin selepas log masuk

This improved solution creates the destination directory if it doesn't exist and ensures proper error handling for all file descriptors and closure cleanup.

Additional Considerations

The updated code also includes ZipSlip detection to prevent directory traversal and potential security risks associated with extracting files outside of the designated destination path.

Atas ialah kandungan terperinci Bagaimanakah saya boleh menyahzip fail dalam Go dengan cekap dengan pengendalian ralat dan pertimbangan keselamatan yang betul?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan