Allow serving custom error page

This commit is contained in:
Gnarwhal 2024-10-12 16:33:22 +00:00
parent bef866faae
commit df06003584
Signed by: Gnarwhal
GPG key ID: 0989A73D8C421174
2 changed files with 27 additions and 1 deletions

View file

@ -4,6 +4,8 @@ import (
_ "embed"
"net/http"
"text/template" // do not use html/template here, we sanitize the message before passing it to the template
"os"
"path"
"codeberg.org/codeberg/pages/server/context"
"github.com/microcosm-cc/bluemonday"
@ -14,7 +16,7 @@ import (
var errorPage string
var (
errorTemplate = template.Must(template.New("error").Parse(errorPage))
errorTemplate = template.Must(template.New("error").Parse(loadCustomTemplateOrDefault()))
sanitizer = createBlueMondayPolicy()
)
@ -51,3 +53,19 @@ func createBlueMondayPolicy() *bluemonday.Policy {
return p
}
func loadCustomTemplateOrDefault() string {
contents, err := os.ReadFile("custom/error.html")
if err != nil {
if !os.IsNotExist(err) {
wd, wdErr := os.Getwd()
if wdErr != nil {
log.Err(err).Msg("could not load custom error page 'custom/error.html'")
} else {
log.Err(err).Msgf("could not load custom error page '%v'", path.Join(wd, "custom/error.html"))
}
}
return errorPage
}
return string(contents)
}