From 5a2f3b35baeacff0c88c4455897f5edef9e6190f Mon Sep 17 00:00:00 2001 From: f0x52 Date: Mon, 21 Jun 2021 21:08:02 +0200 Subject: [PATCH] add 404 handler (#57) --- internal/router/router.go | 7 +++++++ internal/web/base.go | 20 ++++++++++++++++++++ web/template/404.tmpl | 11 +++++++++++ 3 files changed, 38 insertions(+) create mode 100644 web/template/404.tmpl diff --git a/internal/router/router.go b/internal/router/router.go index e575b11..1b8d899 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -42,6 +42,8 @@ type Router interface { AttachHandler(method string, path string, f gin.HandlerFunc) // Attach a gin middleware to the router that will be used globally AttachMiddleware(handler gin.HandlerFunc) + // Attach 404 NoRoute handler + AttachNoRouteHandler(handler gin.HandlerFunc) // Start the router Start() // Stop the router @@ -109,6 +111,11 @@ func (r *router) AttachMiddleware(middleware gin.HandlerFunc) { r.engine.Use(middleware) } +// AttachNoRouteHandler attaches a gin.HandlerFunc to NoRoute to handle 404's +func (r *router) AttachNoRouteHandler(handler gin.HandlerFunc) { + r.engine.NoRoute(handler) +} + // New returns a new Router with the specified configuration, using the given logrus logger. func New(config *config.Config, logger *logrus.Logger) (Router, error) { lvl, err := logrus.ParseLevel(config.LogLevel) diff --git a/internal/web/base.go b/internal/web/base.go index e54150e..8b21527 100644 --- a/internal/web/base.go +++ b/internal/web/base.go @@ -68,6 +68,22 @@ func (m *Module) baseHandler(c *gin.Context) { }) } +func (m *Module) NotFoundHandler(c *gin.Context) { + l := m.log.WithField("func", "404") + l.Trace("serving 404 html") + + instance, err := m.processor.InstanceGet(m.config.Host) + if err != nil { + l.Debugf("error getting instance from processor: %s", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"}) + return + } + + c.HTML(404, "404.tmpl", gin.H{ + "instance": instance, + }) +} + // Route satisfies the RESTAPIModule interface func (m *Module) Route(s router.Router) error { @@ -81,5 +97,9 @@ func (m *Module) Route(s router.Router) error { // serve front-page s.AttachHandler(http.MethodGet, "/", m.baseHandler) + + // 404 handler + s.AttachNoRouteHandler(m.NotFoundHandler) + return nil } diff --git a/web/template/404.tmpl b/web/template/404.tmpl new file mode 100644 index 0000000..49582e6 --- /dev/null +++ b/web/template/404.tmpl @@ -0,0 +1,11 @@ +{{ template "header.tmpl" .}} + + +
+

404: Page Not Found

+ If you believe this was an error, you can contact an admin +
+ +{{ template "footer.tmpl" .}} \ No newline at end of file