forked from eswaribala/rps_cis_go_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArchiveExtract.go
72 lines (65 loc) · 1.54 KB
/
ArchiveExtract.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// This example uses zip but standard library
// also supports tar archives
package main
import (
"archive/zip"
"log"
"io"
"os"
"path/filepath"
)
func main() {
// Create a reader out of the zip archive
zipReader, err := zip.OpenReader("test.zip")
if err != nil {
log.Fatal(err)
}
defer zipReader.Close()
// Iterate through each file/dir found in
for _, file := range zipReader.Reader.File {
// Open the file inside the zip archive
// like a normal file
zippedFile, err := file.Open()
if err != nil {
log.Fatal(err)
}
defer zippedFile.Close()
// Specify what the extracted file name should be.
// You can specify a full path or a prefix
// to move it to a different directory.
// In this case, we will extract the file from
// the zip to a file of the same name.
targetDir := "./"
extractedFilePath := filepath.Join(
targetDir,
file.Name,
)
// Extract the item (or create directory)
if file.FileInfo().IsDir() {
// Create directories to recreate directory
// structure inside the zip archive. Also
// preserves permissions
log.Println("Creating directory:", extractedFilePath)
os.MkdirAll(extractedFilePath, file.Mode())
} else {
// Extract regular file since not a directory
log.Println("Extracting file:", file.Name)
// Open an output file for writing
outputFile, err := os.OpenFile(
extractedFilePath,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
file.Mode(),
)
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
// "Extract" the file by copying zipped file
// contents to the output file
_, err = io.Copy(outputFile, zippedFile)
if err != nil {
log.Fatal(err)
}
}
}
}