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
+25.3k Golang : Find files by extension
+5.1k Golang : How to write backslash in string?
+16.5k How to enable MariaDB/MySQL logs ?
+4.8k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+7.4k Swift : Convert (cast) Character to Integer?
+21.3k Golang : untar or extract tar ball archive example
+4.6k Golang : What is StructTag and how to get StructTag's value?
+14.6k Golang : Loop each day of the current month example
+20.2k Golang : Convert(cast) string to rune and back to string example
+9.7k Golang : Command line file upload program to server example
+5k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+17.2k Golang : Implement getters and setters