66 lines
1.6 KiB
Go
66 lines
1.6 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) badRequestError(w http.ResponseWriter, r *http.Request, err error) {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
var response = api.ErrorResponse{
|
|
Code: http.StatusBadRequest,
|
|
Message: err.Error(),
|
|
}
|
|
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
|
|
}
|