From 12e1c7a523b3bfbb790b67f5e47bc771d24ece2e Mon Sep 17 00:00:00 2001 From: Maxime Delporte Date: Fri, 24 Oct 2025 14:47:20 +0200 Subject: [PATCH] Updating createMovieHandler using helper's readJSON method. --- cmd/api/helpers.go | 2 +- cmd/api/movies.go | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cmd/api/helpers.go b/cmd/api/helpers.go index ac32b42..9caf819 100644 --- a/cmd/api/helpers.go +++ b/cmd/api/helpers.go @@ -86,7 +86,7 @@ func (app *application) writeJSON(w http.ResponseWriter, status int, data envelo } func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst any) error { - // Decode the request body into the target destination. + // Initialize a new json.Decoder instance which reads from the request body, and then use the Decode() method to decode the body contents into the input struct. err := json.NewDecoder(r.Body).Decode(dst) if err != nil { // If there is an error during decoding, start the triage... diff --git a/cmd/api/movies.go b/cmd/api/movies.go index 55fa179..158afad 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -1,7 +1,6 @@ package main import ( - "encoding/json" "fmt" "greenlight.craftr.fr/internal/data" "net/http" @@ -18,8 +17,8 @@ func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Reques Genres []string `json:"genres"` } - // Initialize a new json.Decoder instance which reads from the request body, and then use the Decode() method to decode the body contents into the input struct. Importantly, notice that when we call Decode() we pass a *pointer* to the input struct as the target decode destination. If there was an error during decoding, we also use our generic errorResponse() helper to send the client a 400 Bad Request response containing the error message. - err := json.NewDecoder(r.Body).Decode(&input) + // Use the new readJSON() helper to decode the request body into the input struct. If this returns an error, we send the client the error message along with a 400 Bad Request status code, just like before. + err := app.readJSON(w, r, &input) if err != nil { app.errorResponse(w, r, http.StatusBadRequest, err.Error()) return