Updating createMovieHandler using helper's readJSON method.
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 52s

This commit is contained in:
Maxime Delporte
2025-10-24 14:47:20 +02:00
parent c6baa807e4
commit 12e1c7a523
2 changed files with 3 additions and 4 deletions

View File

@@ -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...

View File

@@ -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