Skip to content

Commit

Permalink
add 404 handler (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
f0x52 authored Jun 21, 2021
1 parent eaeceb1 commit 5a2f3b3
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
7 changes: 7 additions & 0 deletions internal/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 20 additions & 0 deletions internal/web/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand All @@ -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
}
11 changes: 11 additions & 0 deletions web/template/404.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{{ template "header.tmpl" .}}

<aside class="left logo">
<img src="/assets/sloth.png" alt="Clipart styled sloth logo">
</aside>
<section>
<h1>404: Page Not Found</h1>
If you believe this was an error, you can <a href="/{{.instance.ContactAccount}}">contact an admin</a>
</section>

{{ template "footer.tmpl" .}}

0 comments on commit 5a2f3b3

Please sign in to comment.