diff options
author | Matthew Lemon <y@yulqen.org> | 2024-04-18 11:06:32 +0100 |
---|---|---|
committer | Matthew Lemon <y@yulqen.org> | 2024-04-18 11:06:32 +0100 |
commit | 20560419614e22fbb58567cdb0b88b54caf679f4 (patch) | |
tree | 163df44f07907d865b363db3bc198287ebd3d25f /cmd/web/helpers.go | |
parent | 435742cede199e3c85b5e2eb5a42ccbee4906a05 (diff) |
Adds code from ded-go-core - no database
D2S test app code removed (nginx error).
Adds all go code from `ded-go-core` using the basic Gov.UK UI for a test
page for DED.
Diffstat (limited to 'cmd/web/helpers.go')
-rw-r--r-- | cmd/web/helpers.go | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/cmd/web/helpers.go b/cmd/web/helpers.go new file mode 100644 index 0000000..fc9b8f8 --- /dev/null +++ b/cmd/web/helpers.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "log" + "net/http" + "runtime/debug" +) + +func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) { + var ( + method = r.Method + uri = r.URL.RequestURI() + trace = string(debug.Stack()) + ) + + app.logger.Error(err.Error(), "method", method, "uri", uri, "trace", trace) + log.Printf("Crash! %s %s %s", method, uri, trace) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) +} + +// The clientError helper sends a specific status code and corresponding description +// to the user. We'll use this later in the book to send responses like 400 "Bad +// Request" when there's a problem with the request that the user sent. +func (app *application) clientError(w http.ResponseWriter, status int) { + http.Error(w, http.StatusText(status), status) +} + +// notFound helper is a convenience wrapper around clientError which sends a 404 Not Found response +func (app *application) notFound(w http.ResponseWriter) { + app.clientError(w, http.StatusNotFound) +} + +func (app *application) render(w http.ResponseWriter, r *http.Request, status int, page string, data templateData) { + // retrieve the appropriate template set from the cache based on the page name. + // If no entry exists in the cache with the provided name, create a new error + // and call serverError() helper that we made earlier and return. + ts, ok := app.templateCache[page] + if !ok { + err := fmt.Errorf("the template %s does not exist", page) + app.serverError(w, r, err) + return + } + + // Write out the provided HTTP status code('200 OK', '400 Bad Request', etc). + w.WriteHeader(status) + + err := ts.ExecuteTemplate(w, "base", data) + if err != nil { + app.serverError(w, r, err) + } +} |