Write logic for createElection validation

This commit is contained in:
2024-12-28 17:13:22 +01:00
parent 3df4eac964
commit a22f3e5a71
7 changed files with 338 additions and 24 deletions

View File

@ -1,12 +1,63 @@
package main
import "net/http"
import (
api "code.dlmw.ch/dlmw/qv/internal"
"code.dlmw.ch/dlmw/qv/internal/validator"
"encoding/json"
"errors"
"github.com/go-playground/form/v4"
"net/http"
)
func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) {
var (
method = r.Method
uri = r.URL.RequestURI()
)
app.logger.Error(err.Error(), "method", method, "uri", uri)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
w.WriteHeader(http.StatusInternalServerError)
var response = api.ErrorResponse{
Code: http.StatusInternalServerError,
Details: nil,
Message: "There was an error in the request",
}
json.NewEncoder(w).Encode(response)
}
func (app *application) clientError(w http.ResponseWriter, status int, message string) {
w.WriteHeader(status)
var response = api.ErrorResponse{
Code: http.StatusUnprocessableEntity,
Details: &map[string]interface{}{
"error": message,
},
Message: "There was an error in the request",
}
json.NewEncoder(w).Encode(response)
}
func (app *application) unprocessableEntityError(w http.ResponseWriter, v validator.Validator) {
w.WriteHeader(http.StatusUnprocessableEntity)
var response = api.ErrorResponse{
Code: http.StatusUnprocessableEntity,
Details: &map[string]interface{}{
"fields": v.FieldErrors,
},
Message: "Election data is invalid",
}
json.NewEncoder(w).Encode(response)
}
func (app *application) decodePostForm(r *http.Request, dst any) error {
err := r.ParseForm()
if err != nil {
return err
}
err = app.formDecoder.Decode(dst, r.PostForm)
if err != nil {
var invalidDecoderError *form.InvalidDecoderError
if errors.As(err, &invalidDecoderError) {
panic(err)
}
return err
}
return nil
}