2025-01-08 10:55:27 +01:00

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(s services.IStore) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
getDownload(w, r, s)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
}
func getDownload(w http.ResponseWriter, r *http.Request, s 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(s.GetDir(), 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")
}