Create a writeJSON helper

This commit is contained in:
vinchent 2024-08-13 13:34:53 +02:00
parent b37dcf89fd
commit 011b3a8c0b
4 changed files with 25 additions and 5 deletions

View File

@ -251,7 +251,5 @@ func (app *application) CreateAuthToken(w http.ResponseWriter, r *http.Request)
payload.Error = false payload.Error = false
payload.Message = "Success!" payload.Message = "Success!"
out, _ := json.MarshalIndent(payload, "", "\t") _ = app.writeJSON(w, http.StatusOK, payload)
w.Header().Set("Content-Type", "application/json")
w.Write(out)
} }

View File

@ -27,6 +27,29 @@ func (app *application) readJSON(w http.ResponseWriter, r *http.Request, data in
return nil 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 { func (app *application) badRequest(w http.ResponseWriter, r *http.Request, err error) error {
var payload struct { var payload struct {
Error bool `json:"error"` Error bool `json:"error"`

View File

@ -23,7 +23,7 @@ Login
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="password" class="form-label">Password</label> <label for="password" class="form-label">Password</label>
<input type="text" <input type="password"
id="password" id="password"
name="password" name="password"
autocomplete="password-new" autocomplete="password-new"

View File

@ -1 +0,0 @@
exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2exit status 2