Updating createMovieHandler using helper's readJSON method.
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 52s
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 52s
This commit is contained in:
@@ -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 {
|
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)
|
err := json.NewDecoder(r.Body).Decode(dst)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// If there is an error during decoding, start the triage...
|
// If there is an error during decoding, start the triage...
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"greenlight.craftr.fr/internal/data"
|
"greenlight.craftr.fr/internal/data"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -18,8 +17,8 @@ func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Reques
|
|||||||
Genres []string `json:"genres"`
|
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.
|
// 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 := json.NewDecoder(r.Body).Decode(&input)
|
err := app.readJSON(w, r, &input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
app.errorResponse(w, r, http.StatusBadRequest, err.Error())
|
app.errorResponse(w, r, http.StatusBadRequest, err.Error())
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user