Golang : How to stream file to client(browser) or write to http.ResponseWriter?

Tags : golang stream-file browser client

Problem :

You have a file - such as a PDF or MP3 file that you want to stream/download straight to your user's web browser(client). How to achieve that in Golang?

Solution :

Convert the files to buffer with bytes.NewBuffer() function and write to http.ResponseWriter.

Code fragment taken from previous tutorial on how to generate PDF file.

 func PDF(w http.ResponseWriter, r *http.Request) {


 // grab the generated receipt.pdf file and stream it to browser
 streamPDFbytes, err := ioutil.ReadFile("./receipt.pdf")

 if err != nil {

 b := bytes.NewBuffer(streamPDFbytes)

 // stream straight to client(browser)
 w.Header().Set("Content-type", "application/pdf")

 if _, err := b.WriteTo(w); err != nil { // <----- here!
 fmt.Fprintf(w, "%s", err)

 w.Write([]byte("PDF Generated"))

Affiliate :

Hire Golang Developers

  See also : Golang : Create PDF file from HTML file

Tags : golang stream-file browser client

By Adam Ng
