diff --git a/cmd/api/handlers-api.go b/cmd/api/handlers-api.go index 2813b6f..5567aa0 100644 --- a/cmd/api/handlers-api.go +++ b/cmd/api/handlers-api.go @@ -251,7 +251,5 @@ func (app *application) CreateAuthToken(w http.ResponseWriter, r *http.Request) payload.Error = false payload.Message = "Success!" - out, _ := json.MarshalIndent(payload, "", "\t") - w.Header().Set("Content-Type", "application/json") - w.Write(out) + _ = app.writeJSON(w, http.StatusOK, payload) } diff --git a/cmd/api/helpers.go b/cmd/api/helpers.go index 4c29e4f..7dd8056 100644 --- a/cmd/api/helpers.go +++ b/cmd/api/helpers.go @@ -27,6 +27,29 @@ func (app *application) readJSON(w http.ResponseWriter, r *http.Request, data in return nil } +// writeJSON writes arbitrary data out as JSON +func (app *application) writeJSON( + w http.ResponseWriter, + status int, data interface{}, + headers ...http.Header, +) error { + out, err := json.MarshalIndent(data, "", "\t") + if err != nil { + return err + } + + if len(headers) > 0 { + for k, v := range headers[0] { + w.Header()[k] = v + } + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write(out) + return nil +} + func (app *application) badRequest(w http.ResponseWriter, r *http.Request, err error) error { var payload struct { Error bool `json:"error"` diff --git a/cmd/web/templates/login.page.gohtml b/cmd/web/templates/login.page.gohtml index 4f881b5..019058e 100644 --- a/cmd/web/templates/login.page.gohtml +++ b/cmd/web/templates/login.page.gohtml @@ -23,7 +23,7 @@ Login
-