Golang : How to stream file to client(browser) or write to http.ResponseWriter?
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 {
fmt.Println(err)
os.Exit(1)
}
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"))
}
See also : Golang : Create PDF file from HTML file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.8k Golang : Tutorial on loading GOB and PEM files
+10.9k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+11.1k Golang : Removes punctuation or defined delimiter from the user's input
+12.8k Golang : Transform comma separated string to slice example
+9.6k Golang : How to get username from email address
+25.5k Golang : Get current file path of a file or executable
+12.6k Golang : Encrypt and decrypt data with x509 crypto
+8.1k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+5.6k Golang : If else example and common mistake
+7.5k Golang : Not able to grep log.Println() output
+12.4k Golang : Find and draw contours with OpenCV example
+7.6k Golang : Convert source code to assembly language