From 714295bc0d0f4e1b3f8a5263c2ade1ff4e3e7e8a Mon Sep 17 00:00:00 2001 From: lbenedar Date: Tue, 17 Mar 2026 12:22:29 +0300 Subject: [PATCH] ch4.2 --- cmd/api/errors.go | 4 ++++ cmd/api/helpers.go | 30 ++++++++++++++++++++++++++++++ cmd/api/movies.go | 5 ++--- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/cmd/api/errors.go b/cmd/api/errors.go index 79c7a99..8df28d0 100644 --- a/cmd/api/errors.go +++ b/cmd/api/errors.go @@ -35,3 +35,7 @@ func (app *application) methodNotAllowedResponse(w http.ResponseWriter, r *http. message := fmt.Sprintf("the %s method is not supported for this resource", r.Method) app.errorResponse(w, r, http.StatusMethodNotAllowed, message) } + +func (app *application) badRequestResponse(w http.ResponseWriter, r *http.Request, err error) { + app.errorResponse(w, r, http.StatusBadRequest, err.Error()) +} diff --git a/cmd/api/helpers.go b/cmd/api/helpers.go index f8f7829..29b5785 100644 --- a/cmd/api/helpers.go +++ b/cmd/api/helpers.go @@ -3,6 +3,8 @@ package main import ( "encoding/json" "errors" + "fmt" + "io" "net/http" "strconv" @@ -37,3 +39,31 @@ func (app *application) writeJSON(w http.ResponseWriter, status int, data envelo return nil } + +func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst any) error { + err := json.NewDecoder(r.Body).Decode(dst) + if err != nil { + var syntaxError *json.SyntaxError + var unmarshalTypeError *json.UnmarshalTypeError + var invalidMarshallError *json.InvalidUnmarshalError + + switch { + case errors.As(err, &syntaxError): + return fmt.Errorf("body contains badly-formed JSON (at character %d)", syntaxError.Offset) + case errors.Is(err, io.ErrUnexpectedEOF): + return errors.New("body contains badly-formed JSON") + case errors.As(err, &unmarshalTypeError): + if unmarshalTypeError.Field != "" { + return fmt.Errorf("body contains incorrect JSON type for field %q", unmarshalTypeError.Field) + } + return fmt.Errorf("body contains incorrect JSON type for field (at character %d)", unmarshalTypeError.Offset) + case errors.Is(err, io.EOF): + return errors.New("body must be not empty") + case errors.As(err, &invalidMarshallError): + panic(err) + default: + return err + } + } + return nil +} diff --git a/cmd/api/movies.go b/cmd/api/movies.go index a826b0d..547174e 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -1,7 +1,6 @@ package main import ( - "encoding/json" "fmt" "net/http" "time" @@ -17,9 +16,9 @@ func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Reques Genres []string `json:"genres"` } - err := json.NewDecoder(r.Body).Decode(&input) + err := app.readJSON(w, r, &input) if err != nil { - app.errorResponse(w, r, http.StatusBadRequest, err.Error()) + app.badRequestResponse(w, r, err) return } fmt.Fprintf(w, "%+v\n", input)