Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2021
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.13 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "archive/zip"
  5.     "fmt"
  6.     "io/ioutil"
  7. )
  8.  
  9. type myCloser interface {
  10.     Close() error
  11. }
  12.  
  13. // closeFile is a helper function which streamlines closing
  14. // with error checking on different file types.
  15. func closeFile(f myCloser) {
  16.     err := f.Close()
  17.     check(err)
  18. }
  19.  
  20. // readAll is a wrapper function for ioutil.ReadAll. It accepts a zip.File as
  21. // its parameter, opens it, reads its content and returns it as a byte slice.
  22. func readAll(file *zip.File) []byte {
  23.     fc, err := file.Open()
  24.     check(err)
  25.     defer closeFile(fc)
  26.  
  27.     content, err := ioutil.ReadAll(fc)
  28.     check(err)
  29.  
  30.     return content
  31. }
  32.  
  33. // check is a helper function which streamlines error checking
  34. func check(e error) {
  35.     if e != nil {
  36.         panic(e)
  37.     }
  38. }
  39.  
  40. func main() {
  41.     zipFile := "superman.zip"
  42.     // superman.def
  43.     def := zipFile[:len(zipFile)-4] + ".def"
  44.  
  45.     zf, zerr := zip.OpenReader(zipFile)
  46.     check(zerr)
  47.     defer closeFile(zf)
  48.  
  49.     for _, file := range zf.File {
  50.         //fmt.Printf("%s\n", file.Name)
  51.  
  52.         // print out superman.def contents
  53.         if file.Name == def {
  54.             fmt.Printf("%s\n\n", readAll(file)) // file content
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement