Home > Article > Backend Development > How to set or restore headers from response body in Go?
In the Go language, we often need to set or restore the file header of the HTTP response. By setting file headers, we can control how the browser or client handles the response content. So, in Go, how do you set or restore a file header from the response body? In this article, PHP editor Xinyi will introduce you to the solution to this problem in detail. Whether you are a newbie or an experienced developer, this article will provide you with useful information and sample code to help you tackle this problem with ease. let's start!
I'm having some issues recovering multiple file headers sent in response to a GET request for compression. The main problem here is that I want to get rid of the default date Go sets for the file of "November 30, 1979" (after the file is compressed), and instead of that, I want the current date to be displayed. But I don't know how to modify or even retrieve the headers from the file since I receive the io.ReadCloser type from the response body.
This is the current code
archive := zip.NewWriter(w) attachment := "attachment; filename=someZipFile.zip") c.Writer.Header().Set("Content-Disposition", attachment) for i := 0; i < len(bodies); i++ { // bodies are response bodies, corresponding to "downloaded" files defer bodies[i].Close() fmt.Println(filenames[i]) w, err := archive.Create("someZipFile/" + filenames[i]) if err != nil { fmt.Println("File couldn't be created") return true } if _, err := io.Copy(w, bodies[i]); err != nil { fmt.Println("File couldn't be written") return true } } archive.Close()
I would like to clarify what I can do, whether to create a new header or edit an existing header, and if the former, how to get the file header. In the worst case scenario, figure out a completely new solution.
Create is a helper method that calls CreateHeader. Directly call CreateHeader to specify file metadata:
w, err := archive.CreateHeader(&zip.FileHeader{ Name: "someZipFile/" + filenames[i], Method: zip.Deflate, Modified: time.Now(), })
Change the call to create the archive file as shown below. Use the other code from the question as-is.
The above is the detailed content of How to set or restore headers from response body in Go?. For more information, please follow other related articles on the PHP Chinese website!