Skip to content

Commit

Permalink
server: Refresh the error template
Browse files Browse the repository at this point in the history
We cannot cache it forever, as that will not allow the end user to edit and preview it.
  • Loading branch information
bep committed May 16, 2022
1 parent 87a22eb commit 657d1a2
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions commands/server.go
Expand Up @@ -35,6 +35,8 @@ import (

"github.com/gohugoio/hugo/common/htime"
"github.com/gohugoio/hugo/common/paths"
"github.com/gohugoio/hugo/hugolib"
"github.com/gohugoio/hugo/tpl"
"golang.org/x/sync/errgroup"

"github.com/gohugoio/hugo/livereload"
Expand Down Expand Up @@ -522,20 +524,37 @@ func (c *commandeer) serve(s *serverCmd) error {
roots = []string{""}
}

templHandler := c.hugo().Tmpl()
errTempl, found := templHandler.Lookup("_server/error.html")
if !found {
panic("template server/error.html not found")
// Cache it here. The HugoSites object may be unavaialble later on due to intermitent configuration errors.
// To allow the en user to change the error template while the server is running, we use
// the freshest template we can provide.
var (
errTempl tpl.Template
templHandler tpl.TemplateHandler
)
getErrorTemplateAndHandler := func(h *hugolib.HugoSites) (tpl.Template, tpl.TemplateHandler) {
if h == nil {
return errTempl, templHandler
}
templHandler := h.Tmpl()
errTempl, found := templHandler.Lookup("_server/error.html")
if !found {
panic("template server/error.html not found")
}
return errTempl, templHandler
}
errTempl, templHandler = getErrorTemplateAndHandler(c.hugo())

srv := &fileServer{
baseURLs: baseURLs,
roots: roots,
c: c,
s: s,
errorTemplate: func(ctx any) (io.Reader, error) {
// hugoTry does not block, getErrorTemplateAndHandler will fall back
// to cached values if nil.
templ, handler := getErrorTemplateAndHandler(c.hugoTry())
b := &bytes.Buffer{}
err := templHandler.Execute(errTempl, b, ctx)
err := handler.Execute(templ, b, ctx)
return b, err
},
}
Expand Down

0 comments on commit 657d1a2

Please sign in to comment.