diff --git a/cmd/api/healthcheck.go b/cmd/api/healthcheck.go index c96a662..48c3416 100644 --- a/cmd/api/healthcheck.go +++ b/cmd/api/healthcheck.go @@ -5,10 +5,6 @@ import ( "net/http" ) -/* -Declare a handler which writes a plain-text response with information about the -application status, operating environment and version -*/ /* Tips: The important thing to point out here is that healthcheckHandler is implemented as a method on our application struct. This is an effective and idiomatic way to make dependencies available @@ -17,7 +13,22 @@ healthcheckHandler needs can simply be included as a field in the application st initialize it in main() */ func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, "status: available") - fmt.Fprintf(w, "environment: %s\n", app.config.env) - fmt.Fprintf(w, "version: %s\n", version) + /* + Create a fixed-format JSON response from a string. Notice how we're using a raw + string literal (enclosed with backticks) so that we can include double-quote + characters in the JSON without needing to espace them? We also use the %q verb to + wrap the interpolated values in double-quotes. + */ + js := `{"status": "available", "environment": %q, "version": %q}` + js = fmt.Sprintf(js, app.config.env, version) + + /* + Set the "Content-Type: application/json" header on the response. If you forget to + this, Go will default to sending a "Content-Type: text/plain; charset=utf-8" + header instead. + */ + w.Header().Set("Content-Type", "application/json") + + // Write the JSON as the HTTP response body. + w.Write([]byte(js)) }