Creating writeJSON method inside helpers.go file. Using writeJSON helper inside healthcheckHandler.

This commit is contained in:
Maxime Delporte
2025-10-11 21:15:50 +02:00
parent 0db52ad9de
commit cb3691ce04
2 changed files with 38 additions and 19 deletions

View File

@@ -1,6 +1,7 @@
package main
import (
"encoding/json"
"errors"
"github.com/julienschmidt/httprouter"
"net/http"
@@ -41,3 +42,38 @@ func (app *application) readIDParam(r *http.Request) (int64, error) {
return id, nil
}
/*
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 {
// Encode the data to JSON, returning the error if there was one.
js, err := json.Marshal(data)
if err != nil {
return err
}
// Append a newline to make it easier to view in terminal applications.
js = append(js, '\n')
/*
At this point, we know that we won't encounter any more errors before writing the
response, so it's safe to add any headers that we want to include. We loop
through the header map and add each header to the http.ResponseWriter header map.
Note that it's OK if the provided header map is nil. Go doesn't throw an error
if you try to range over (or generally, read from) a nil map.
*/
for key, value := range headers {
w.Header()[key] = value
}
// And the "Content-Type: application/json" header, then write the status code and
// JSON response.
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(js)
return nil
}