librapi/handlers/upload/handler.go
2025-01-08 10:55:27 +01:00

94 lines
2.0 KiB
Go

package upload
import (
"fmt"
"net/http"
"github.com/rs/zerolog/log"
"librapi/forms"
"librapi/services"
"librapi/templates"
)
const (
URL = "/upload"
)
func Handler(a services.IAuthenticate, s services.IStore) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
getUploadFile(w, r)
case http.MethodPost:
postUploadFile(w, r, a, s)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
}
func postUploadFile(w http.ResponseWriter, r *http.Request, a services.IAuthenticate, s services.IStore) {
if !a.IsLogged(r) {
tmpl, err := templates.ExecuteUploadFormTmpl(&forms.UploadForm{Error: services.ErrUnauthorized.Error()}, w)
if err != nil {
log.Err(err).Msg("unable to generate upload template")
return
}
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, tmpl)
return
}
uf := forms.UploadFormFromRequest(r)
tmpl, err := templates.ExecuteUploadFormTmpl(&uf, w)
if err != nil {
log.Err(err).Msg("unable to generate upload template")
return
}
if uf.HasErrors() {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, tmpl)
return
}
filename := uf.File.Value.GetFilename()
log.Info().Str("filename", filename).Msg("file is uploading...")
resource := uf.IntoResource()
if err := s.Create(resource); err != nil {
uf.Error = err.Error()
tmpl, err := templates.ExecuteUploadFormTmpl(&uf, w)
if err != nil {
log.Err(err).Msg("unable to generate upload template")
return
}
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, tmpl)
return
}
tmpl, err = templates.ExecuteUploadFormTmpl(&forms.UploadForm{Method: http.MethodPost}, w)
if err != nil {
log.Err(err).Msg("unable to generate upload template")
return
}
fmt.Fprint(w, tmpl)
}
func getUploadFile(w http.ResponseWriter, _ *http.Request) {
tmpl, err := templates.ExecuteUploadFormTmpl(&forms.UploadForm{}, w)
if err != nil {
log.Err(err).Msg("unable to generate upload template")
return
}
fmt.Fprint(w, tmpl)
}