Files
qv/cmd/web/helpers.go
2025-01-11 18:29:01 +01:00

57 lines
1.3 KiB
Go

package main
import (
api "code.dlmw.ch/dlmw/qv/internal"
"code.dlmw.ch/dlmw/qv/internal/validator"
"encoding/json"
"io"
"net/http"
)
func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) {
app.logger.Error(err.Error())
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: status,
Details: nil,
Message: message,
}
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: "Request data is invalid",
}
json.NewEncoder(w).Encode(response)
}
func (app *application) unmarshalRequest(r *http.Request, dst any) error {
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &dst)
if err != nil {
return err
}
return nil
}