58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
package download
|
|
|
|
import (
|
|
"fmt"
|
|
"librapi/services"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
const URL = "/download"
|
|
|
|
func Handler(bs services.IStore) func(http.ResponseWriter, *http.Request) {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
getDownload(w, r, bs)
|
|
default:
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
}
|
|
|
|
func getDownload(w http.ResponseWriter, r *http.Request, bs services.IStore) {
|
|
queryParams := r.URL.Query()
|
|
downloadFiles, ok := queryParams["file"]
|
|
if !ok {
|
|
log.Error().Msg("file query param does not exist")
|
|
http.Error(w, "file query param does not exist", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if len(downloadFiles) != 1 {
|
|
log.Error().Msg("only one file is allowed to download")
|
|
http.Error(w, "only one file is allowed to download", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
filename := downloadFiles[0]
|
|
filePath := filepath.Join(bs.GetStoreDir(), filename)
|
|
|
|
if _, err := os.Stat(filePath); err != nil {
|
|
if os.IsNotExist(err) {
|
|
http.Error(w, "file does not exist", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
http.Error(w, "unexpected error occurred", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
http.ServeFile(w, r, filePath)
|
|
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
|
|
w.Header().Set("Content-Type", "application/pdf")
|
|
}
|