Creating an envelope struct type inside our helpers file to update our writeJSON data type method's parameter. Updating healthcheckHandler and showMovieHandler with this new type to update our responses.

This commit is contained in:
Maxime Delporte
2025-10-19 11:47:25 +02:00
parent d7ccef3713
commit 1927c64047
4 changed files with 16 additions and 5 deletions

View File

@@ -13,13 +13,13 @@ initialize it in main()
*/
func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Request) {
// Create a map which holds the information that we want to send in the response.
data := map[string]string{
env := envelope{
"status": "available",
"environment": app.config.env,
"version": version,
}
err := app.writeJSON(w, http.StatusOK, data, nil)
err := app.writeJSON(w, http.StatusOK, env, nil)
if err != nil {
app.logger.Error(err.Error())
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)

View File

@@ -43,12 +43,14 @@ func (app *application) readIDParam(r *http.Request) (int64, error) {
return id, nil
}
type envelope map[string]any
/*
Define a writeJSON() helper for sending responses. This takes the destination
http.ResponseWriter, the HTTP status code to send, the data to encode to JSON, and a
header map containing any additional HTTP headers we want to include in the response.
*/
func (app *application) writeJSON(w http.ResponseWriter, status int, data any, headers http.Header) error {
func (app *application) writeJSON(w http.ResponseWriter, status int, data envelope, headers http.Header) error {
/*
Use the json.MarshalIndent() function so that whitespace is added to
the encoded JSON. Here we use no line prefix ("") and tab indents ("\t") for each element.

View File

@@ -36,7 +36,7 @@ func (app *application) showMovieHandler(w http.ResponseWriter, r *http.Request)
}
// Encode the struct to JSON and send it as the HTTP response.
err = app.writeJSON(w, http.StatusOK, movie, nil)
err = app.writeJSON(w, http.StatusOK, envelope{"movie": movie}, nil)
if err != nil {
app.logger.Error(err.Error())
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)