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
+9.2k Golang : Serving HTTP and Websocket from different ports in a program example
+15.3k Golang : Get timezone offset from date or timestamp
+13.4k Golang : Linear algebra and matrix calculation example
+14.8k Golang : Normalize unicode strings for comparison purpose
+10.6k Golang : ISO8601 Duration Parser example
+12.4k Golang : Search and extract certain XML data example
+10.1k Golang : Compare files modify date example
+4.3k Javascript : How to show different content with noscript?
+13.4k Golang : error parsing regexp: invalid or unsupported Perl syntax
+14k Golang : Google Drive API upload and rename example
+8.7k Golang : Find duplicate files with filepath.Walk
+14k Golang : Human readable time elapsed format such as 5 days ago