I'm serving some files dynamically using golang and the following code handles the actual serving of files:
data, err := ioutil.ReadFile(file.Path)
logo.RuntimeError(err)
http.ServeContent(w, r, file.Name, time.Now(), bytes.NewReader(data))
Within the previous code "file" is simply a custom struct holding various information about the file.
The only problem with this code is that it results in me downloading a file called "download" whenever I call the specific handler. I'd like to give the file the user is downloading a custom name, or, rather, signify in a way that is as browser neutral as possible that I want the file to have a certain name.
I assume this might be doable using w.WriteHeader ? But I've been unable to find any examples or clear guidelines on how to do this.
Set the content disposition header before serving the content:
f, err := os.Open(file.Path)
if err != nil {
// handle error
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
// handle error
}
w.Header().Set("Content-Disposition", "attachment; filename=YOURNAME")
http.ServeContent(w, r, file.Name, fi.ModTime(), f)
Note that this code passes an *os.File directly to ServeContent instead of reading the entire file to memory.
The code can be simplified further by calling ServeFile:
w.Header().Set("Content-Disposition", "attachment; filename=YOURNAME")
http.ServeFile(w, r, file.Name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With