Created
May 1, 2023 13:14
-
-
Save robherley/7d2ee8f6c34ca18d59f39f856947c676 to your computer and use it in GitHub Desktop.
Streaming combine zips
This file contains hidden or 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" | |
"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