Go standard library has archive/zip
package for reading and creating ZIP archives.
Last active
June 29, 2020 08:45
-
-
Save kjk/efa13acbaa94b10c35c83b498e7c9edf to your computer and use it in GitHub Desktop.
Create ZIP file in Go (made with https://codeeval.dev)
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" | |
"log" | |
"os" | |
"path/filepath" | |
) | |
func zipAddFile(zw *zip.Writer, filePath string, pathInZip string) error { | |
f, err := os.Open(filePath) | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
if pathInZip == "" { | |
pathInZip = filepath.Base(filePath) | |
} | |
w, err := zw.Create(pathInZip) | |
if err != nil { | |
return err | |
} | |
_, err = io.Copy(w, f) | |
return err | |
} | |
func main() { | |
fw, err := os.Create("out.zip") | |
if err != nil { | |
log.Fatalf("os.Create() failed with '%s'\n", err) | |
} | |
zw := zip.NewWriter(fw) | |
err = zipAddFile(zw, "create_zip_file.go", "") | |
if err != nil { | |
log.Fatalf("zipAddFile() failed with '%s'\n", err) | |
} | |
err = zipAddFile(zw, "create_zip_file.go", "another copy.go") | |
if err != nil { | |
log.Fatalf("zipAddFile() failed with '%s'\n", err) | |
} | |
_ = zw.Close() | |
_ = fw.Close() | |
printFileName("out.zip") | |
} | |
func printFileName(filePath string) { | |
st, _ := os.Stat(filePath) | |
fmt.Printf("Size of file '%s' is %d bytes\n", filePath, st.Size()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment