From 147bbb3e81db0815e196f253ef80afd7e0ca19ae Mon Sep 17 00:00:00 2001 From: ergz Date: Mon, 19 Jun 2023 02:24:23 -0700 Subject: [PATCH] start using Marshal for creating json responses --- cmd/api/healthcheck.go | 25 +++++++++++++++++++++---- cmd/api/helpers.go | 20 ++++++++++++++++++++ cmd/api/movies.go | 7 +------ 3 files changed, 42 insertions(+), 10 deletions(-) create mode 100644 cmd/api/helpers.go diff --git a/cmd/api/healthcheck.go b/cmd/api/healthcheck.go index 0be3022..e404edd 100644 --- a/cmd/api/healthcheck.go +++ b/cmd/api/healthcheck.go @@ -1,13 +1,30 @@ package main import ( - "fmt" + "encoding/json" "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", version) + + // create a mapping that will be converted to json + data := map[string]string{ + "status": "available", + "environment": app.config.env, + "version": version, + } + + js, err := json.Marshal(data) + if err != nil { + app.logger.Print(err) + http.Error(w, "the server encountered an error and could process your request", http.StatusInternalServerError) + return + } + + js = append(js, '\n') + + w.Header().Set("Content-Type", "application/json") + + w.Write(js) } diff --git a/cmd/api/helpers.go b/cmd/api/helpers.go new file mode 100644 index 0000000..b3d3b04 --- /dev/null +++ b/cmd/api/helpers.go @@ -0,0 +1,20 @@ +package main + +import ( + "errors" + "net/http" + "strconv" + + "github.com/julienschmidt/httprouter" +) + +func (app *application) readIDParam(r *http.Request) (int64, error) { + params := httprouter.ParamsFromContext(r.Context()) + + id, err := strconv.ParseInt(params.ByName("id"), 10, 64) + if err != nil || id < 1 { + return 0, errors.New("invalid id parameter") + } + + return id, nil +} diff --git a/cmd/api/movies.go b/cmd/api/movies.go index f1ec73d..e4e5b95 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -3,9 +3,6 @@ package main import ( "fmt" "net/http" - "strconv" - - "github.com/julienschmidt/httprouter" ) func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Request) { @@ -13,9 +10,7 @@ func (app *application) createMovieHandler(w http.ResponseWriter, r *http.Reques } func (app *application) showMovieHandler(w http.ResponseWriter, r *http.Request) { - params := httprouter.ParamsFromContext(r.Context()) - - id, err := strconv.ParseInt(params.ByName("id"), 10, 64) + id, err := app.readIDParam(r) if err != nil { http.NotFound(w, r) return