add download handler
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
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")
|
||||
}
|
||||
Reference in New Issue
Block a user