Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
32
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

Go言語でzipファイル解凍

archive/zipパッケージが用意されているので簡単に実装できるかと思いきや、サンプルも見つからずに苦労したので投稿しました。

main.go
package main

import (
    "archive/zip"
    "io"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
)

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

    for _, f := range r.File {
        rc, err := f.Open()
        if err != nil {
            return err
        }
        defer rc.Close()

        if f.FileInfo().IsDir() {
            path := filepath.Join(dest, f.Name)
            os.MkdirAll(path, f.Mode())
        } else {
            buf := make([]byte, f.UncompressedSize)
            _, err = io.ReadFull(rc, buf)
            if err != nil {
                return err
            }

            path := filepath.Join(dest, f.Name)
            if err = ioutil.WriteFile(path, buf, f.Mode()); err != nil {
                return err
            }
        }
    }

    return nil
}

func main() {
    err := Unzip("./sample.zip", "./out")
    if err != nil {
        log.Fatal(err)
    }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
32
Help us understand the problem. What are the problem?