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
+5.5k Golang : Lock executable to a specific machine with unique hash of the machine
+8.6k Golang : Generate random integer or float number
+13.7k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+22.5k Golang : Storing cookies in http.CookieJar example
+9.9k Golang : Clean formatting/indenting or pretty print JSON result
+4.2k Golang : Use NLP to get sentences for each paragraph example
+5.9k Golang : Ways to recover memory during run time.
+6.7k Golang : How To Use Panic and Recover
+7k Golang : Gorilla web tool kit schema example
+21.8k Golang : Upload to S3 with official aws-sdk-go package
+9.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+6.9k Golang : Capture text return from exec function example