programming

18 How to Download File in Golang

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.

func DownloadFileHandler(w http.ResponseWriter, r *http.Request) {
	fileName := r.URL.Query().Get("file")
	if fileName == "" {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, "Bad Request")
	}

	w.Header().Add("Content-Disposition", "attachment;filename=\""+fileName+"\"")
	http.ServeFile(w, r, "./resources/"+fileName)
}

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

mux.HandleFunc("/download", DownloadFileHandler)

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

http://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

comments powered by Disqus