2025-01-07 11:53:14 +01:00

48 lines
1.1 KiB
Go

package download
import (
"fmt"
"librapi/services"
"net/http"
"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 does not exists", 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)
http.ServeFile(w, r, filePath)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
w.Header().Set("Content-Type", "application/pdf")
}