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
+12.2k Golang : convert rune to unicode hexadecimal value and back to rune character
+30k Golang : Converting a negative number to positive number
+11.8k Swift : Convert (cast) Int to String ?
+13.9k Golang : How to reverse elements order in map ?
+5.5k Golang : Reverse by word
+7.8k Golang : Temperatures conversion example
+5.6k Golang : Decode XML data from RSS feed
+5.7k Golang : constant 20013 overflows byte error message
+3.5k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+21.2k Golang : Fix type interface{} has no field or no methods and type assertions example
+5.8k Golang : How to stop user from directly running an executable file?
+19.1k Golang : Create and resolve(read) symbolic links