Updating healthcheckHandler using json.Marshal method instead of raw json string.
This commit is contained in:
@@ -1,7 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -13,22 +13,32 @@ healthcheckHandler needs can simply be included as a field in the application st
|
|||||||
initialize it in main()
|
initialize it in main()
|
||||||
*/
|
*/
|
||||||
func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Request) {
|
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.
|
||||||
Create a fixed-format JSON response from a string. Notice how we're using a raw
|
data := map[string]string{
|
||||||
string literal (enclosed with backticks) so that we can include double-quote
|
"status": "available",
|
||||||
characters in the JSON without needing to espace them? We also use the %q verb to
|
"environment": app.config.env,
|
||||||
wrap the interpolated values in double-quotes.
|
"version": version,
|
||||||
*/
|
}
|
||||||
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
|
Pass the map to the json.Marshal() function. This returns a []byte slice
|
||||||
this, Go will default to sending a "Content-Type: text/plain; charset=utf-8"
|
containing the encoded JSON. If there was an error, we log it and send the client
|
||||||
header instead.
|
a generic error message.
|
||||||
*/
|
*/
|
||||||
|
js, err := json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
app.logger.Error(err.Error())
|
||||||
|
http.Error(w, "The server encountered a problem and could not process your request.", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append a newline to the JSON. This is just a small nicety to make it easier to
|
||||||
|
// view in terminal applications.
|
||||||
|
js = append(js, '\n')
|
||||||
|
|
||||||
|
// At this point, we know that encoding the data worked without any problem, so we
|
||||||
|
// can safely set any necessary HTTP headers for a successful response.
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
|
||||||
// Write the JSON as the HTTP response body.
|
// Use w.Write() to send the []byte slice containing the JSON as the response body.
|
||||||
w.Write([]byte(js))
|
w.Write(js)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user