diff --git a/cmd/api/healthcheck.go b/cmd/api/healthcheck.go index 68bed0d..e6876be 100644 --- a/cmd/api/healthcheck.go +++ b/cmd/api/healthcheck.go @@ -1,12 +1,18 @@ package main import ( - "fmt" "net/http" ) 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) + data := map[string]string{ + "status": "available", + "environment": app.config.env, + "version": version, + } + err := app.writeJSON(w, http.StatusOK, data, nil) + if err != nil { + app.logger.Print(err) + http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError) + } } diff --git a/cmd/api/helpers.go b/cmd/api/helpers.go index 3101377..072e7fa 100644 --- a/cmd/api/helpers.go +++ b/cmd/api/helpers.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "errors" "net/http" "strconv" @@ -17,3 +18,20 @@ func (app *application) readIDParam(r *http.Request) (int64, error) { } return id, nil } + +func (app *application) writeJSON(w http.ResponseWriter, status int, data any, headers http.Header) error { + js, err := json.Marshal(data) + if err != nil { + return err + } + js = append(js, '\n') + for key, value := range headers { + w.Header()[key] = value + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write(js) + + return nil +} diff --git a/cmd/api/routes.go b/cmd/api/routes.go index ade1227..0dc2429 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -9,7 +9,7 @@ import ( func (app *application) routes() *httprouter.Router { router := httprouter.New() - router.HandlerFunc(http.MethodGet, "/v1/healtcheck", app.healthcheckHandler) + router.HandlerFunc(http.MethodGet, "/v1/healthcheck", app.healthcheckHandler) router.HandlerFunc(http.MethodPost, "/v1/movies", app.createMovieHandler) router.HandlerFunc(http.MethodGet, "/v1/movies/:id", app.showMovieHandler)