Hello to all.

The issue is related to the development of the golang backend site. Before that, I wrote a similar thing on nodejs. For him, there is such a module that allows you to create archives. The archive object has a pipe method that can be used to redirect the archive stream to the response stream immediately.

Why is it good? The site user does not wait for the end of archive creation on the server, but immediately starts downloading. Thus implemented download on many sites.

How can this functionality be implemented using the go language? Now using archive/zip I do this (following the example on the site ):

 buf := new(bytes.Buffer) writer := zip.NewWriter(buf) f, _ := writer.Create(name) fileBytes, err := ioutil.ReadFile(pathToFile) f.Write(fileBytes) writer.Close() http.ServeContent(writer, request, zipName, time.Now(), bytes.NewReader(buf.Bytes())) 

(Extra checks removed intentionally so as not to overload the code)

But, of course, now the site user has to wait for the complete creation of the archive. Is there any option to do better?

    1 answer 1

    zip.NewWriter accepts zip.NewWriter as its input, to which http.ResponseWriter satisfies. Given that the file is io.Reader 'om, you can use io.Copy in your http.Handler ' e to not read the entire file.

     zw := zip.NewWriter(w) // где w - это http.ResponseWriter zf, err := zw.Create(name) // проверка err _, err = io.Copy(zf, f) // где f - это *os.File или другой io.Reader // проверка err err = zw.Close() // проверка err 
    • Wow, how beautiful)) Thank you - Alik Send