Skip to content

Instantly share code, notes, and snippets.

@Shamil-R
Created January 30, 2024 08:26
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 Shamil-R/31109c145f0e8201d82c2e0aa5418980 to your computer and use it in GitHub Desktop.
Save Shamil-R/31109c145f0e8201d82c2e0aa5418980 to your computer and use it in GitHub Desktop.
empty dir in zip
package main
import (
"archive/zip"
"fmt"
"net/http"
)
func addEmptyDirectoryToZip(zipWriter *zip.Writer, directoryName string) error {
header := &zip.FileHeader{
Name: directoryName + "/",
Method: zip.Store,
}
writer, err := zipWriter.CreateHeader(header)
if err != nil {
return err
}
_, err = writer.Write([]byte{})
return err
}
func createZipAndWriteToResponse(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", "attachment; filename=example.zip")
zipWriter := zip.NewWriter(w)
defer zipWriter.Close()
err := addEmptyDirectoryToZip(zipWriter, "empty_folder")
if err != nil {
fmt.Println(err)
http.Error(w, "Failed to add directory to zip", http.StatusInternalServerError)
return
}
fmt.Println("Archive created")
}
func main() {
http.HandleFunc("/download", createZipAndWriteToResponse)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment