A
A
Alexander Melentyev2020-03-02 23:56:44
go
Alexander Melentyev, 2020-03-02 23:56:44

How to save the result of code generation to the archive and immediately give it away?

Hello.
There is a rest API, when accessing a certain endpoint, it is planned to do several code generations, and put the results in the form of ready-made files into an archive and give them to the requested one. How to save the result of code generation to the archive and immediately give it away?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WinPooh32, 2020-03-03
@asmelentyev

https://golang.org/pkg/archive/zip/
Single file example:

func handle(w http.ResponseWriter, r *http.Request){
  fileToZip, _ := os.Open("filepath")
  defer fileToZip.Close()

  // NewWriter returns a new Writer writing a zip file to w.
  zipWriter := zip.NewWriter(w)
  defer zipWriter.Close()

  info, _ := fileToZip.Stat()

  header, _ := zip.FileInfoHeader(info)

  // Change to deflate to gain better compression
  // see http://golang.org/pkg/archive/zip/#pkg-constants
  header.Method = zip.Deflate

  // CreateHeader adds a file to the zip archive using the provided FileHeader
  // for the file metadata. 
  // This returns a Writer to which the file contents should be written.
  writer, _ := zipWriter.CreateHeader(header)
  io.Copy(writer, fileToZip)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question