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
+23.8k Golang : Fix type interface{} has no field or no methods and type assertions example
+6k Golang : Missing Subversion command
+16k Golang : Get sub string example
+19.3k Golang : Fix cannot download, $GOPATH not set error
+34.5k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+16k Golang : How to check if input from os.Args is integer?
+21.1k Golang : Get password from console input without echo or masked
+14.3k Golang : Parsing or breaking down URL
+16.5k Golang : Delete files by extension
+5.3k Golang : Return multiple values from function
+11.1k CodeIgniter : How to check if a session exist in PHP?
+13.7k Golang : How to determine if a year is leap year?