Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang communicating the name of the file served to the browser/client

Tags:

file

http

server

go

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.

like image 736
George Avatar asked Dec 24 '22 17:12

George


1 Answers

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)
like image 54
Bayta Darell Avatar answered Dec 27 '22 05:12

Bayta Darell