Skip to content

Instantly share code, notes, and snippets.

@robherley
Created May 1, 2023 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robherley/7d2ee8f6c34ca18d59f39f856947c676 to your computer and use it in GitHub Desktop.
Save robherley/7d2ee8f6c34ca18d59f39f856947c676 to your computer and use it in GitHub Desktop.
Streaming combine zips
package main
import (
"archive/zip"
"io"
"net/http"
"path/filepath"
)
func downloadZips(w io.Writer) error {
zwrite := zip.NewWriter(w)
defer zwrite.Close()
zipFiles, err := filepath.Glob("archive*.zip")
if err != nil {
return err
}
for _, zipFile := range zipFiles {
zipReader, err := zip.OpenReader(zipFile)
if err != nil {
return err
}
defer zipReader.Close()
for _, file := range zipReader.File {
f, err := file.Open()
if err != nil {
return err
}
defer f.Close()
fw, err := zwrite.Create(file.Name)
if err != nil {
return err
}
_, err = io.Copy(fw, f)
if err != nil {
return err
}
}
}
return nil
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", "attachment; filename=artifact.zip")
err := downloadZips(w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
http.ListenAndServe("localhost:8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment