Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
10 Sep 2023 · 1 min read ·Article 48 / 119
Go

18 How to Download File in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Download Files

Apart from uploading files, we also need or need a page that can download files or something on our website. The Golang library provides FileServer and ServeFile. If we want to force the file to be downloaded without having to be rendered by the browser then we can use the Content-Disposition header. More details can be seen on this page https://developer.mozilla.org/en-US/docs/Web/Headers/Content-Disposition .

How to Implement in Golang

Let’s just continue by creating a download page by creating a handler function like the one below.

go
 1func DownloadFileHandler(w http.ResponseWriter, r *http.Request) {
 2	fileName := r.URL.Query().Get("file")
 3	if fileName == "" {
 4		w.WriteHeader(http.StatusBadRequest)
 5		fmt.Fprint(w, "Bad Request")
 6	}
 7
 8	w.Header().Add("Content-Disposition", "attachment;filename=\""+fileName+"\"")
 9	http.ServeFile(w, r, "./resources/"+fileName)
10}

Add the above function to the mux router in the main.go file as below.

go
1mux.HandleFunc("/download", DownloadFileHandler)

Run it and open a browser, try accessing the page below.

bash
1http://localhost:8080/download?file=tutorial-golang.webp

Then it will immediately download the target file in the resources folder according to the file sent in the parameters.

tutorial golang web download file

Related Articles

💬 Comments