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
+10.1k Generate Random number with math/rand in Go
+12.9k Facebook PHP getUser() returns 0
+4k Javascript : How to show different content with noscript?
+20.6k Golang : Get password from console input without echo or masked
+84.9k Golang : How to convert character to ASCII and back
+5.2k Golang : Frobnicate or tweaking a string example
+9.4k Golang : List available AWS regions
+18k Golang : Iterating Elements Over A List
+2.9k Golang : Fix go-cron set time not working issue
+11.8k Golang : Print UTF-8 fonts on image example
+6k Golang : Break string into a slice of characters example
+11.5k Golang : Detect user location with HTML5 geo-location