64 lines
1.5 KiB
Go

package frontend
import (
"fmt"
"log"
"net/http"
"path/filepath"
"github.com/google/uuid"
b "streifling.com/jason/cpolis/cmd/backend"
)
func UploadPDF(c *b.Config, s *b.CookieStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, err := getSession(w, r, c, s); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file, _, err := r.FormFile("pdf-upload")
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
buffer := make([]byte, 512) // Should be enough for mime type
if _, err := file.Read(buffer); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := file.Seek(0, 0); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if http.DetectContentType(buffer) != "application/pdf" {
http.Error(w, "Die Datei ist kein PDF.", http.StatusBadRequest)
return
}
filename := fmt.Sprint(uuid.New(), ".pdf")
absFilepath, err := filepath.Abs(c.PDFDir + "/" + filename)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = b.WriteFile(absFilepath, file); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
}