-
-
Save prostoiChelovek/779a826e0c1e0d2dddd02ff4b2abb734 to your computer and use it in GitHub Desktop.
golang: Read zip file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"archive/zip" | |
"fmt" | |
"io/ioutil" | |
) | |
type myCloser interface { | |
Close() error | |
} | |
// closeFile is a helper function which streamlines closing | |
// with error checking on different file types. | |
func closeFile(f myCloser) { | |
err := f.Close() | |
check(err) | |
} | |
// readAll is a wrapper function for ioutil.ReadAll. It accepts a zip.File as | |
// its parameter, opens it, reads its content and returns it as a byte slice. | |
func readAll(file *zip.File) []byte { | |
fc, err := file.Open() | |
check(err) | |
defer closeFile(fc) | |
content, err := ioutil.ReadAll(fc) | |
check(err) | |
return content | |
} | |
// check is a helper function which streamlines error checking | |
func check(e error) { | |
if e != nil { | |
panic(e) | |
} | |
} | |
func main() { | |
zipFile := "myzipfile.zip" | |
zf, err := zip.OpenReader(zipFile) | |
check(err) | |
defer closeFile(zf) | |
for _, file := range zf.File { | |
fmt.Printf("=%s\n", file.Name) | |
fmt.Printf("%s\n\n", readAll(file)) // file content | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment