mirror of
https://codeberg.org/Codeberg/pages-server.git
synced 2025-04-24 22:06:57 +00:00
add go templating engine for error page and make errors more clear
This commit is contained in:
parent
7f0a4e5ca9
commit
9346dbfba9
15 changed files with 228 additions and 201 deletions
52
html/html.go
52
html/html.go
|
@ -1,9 +1,51 @@
|
|||
package html
|
||||
|
||||
import _ "embed"
|
||||
import (
|
||||
_ "embed"
|
||||
"html/template"
|
||||
"net/http"
|
||||
|
||||
//go:embed 404.html
|
||||
var NotFoundPage string
|
||||
"codeberg.org/codeberg/pages/server/context"
|
||||
"github.com/microcosm-cc/bluemonday"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
//go:embed error.html
|
||||
var ErrorPage string
|
||||
//go:embed templates/error.html
|
||||
var errorPage string
|
||||
|
||||
var errorTemplate = template.Must(template.New("error").Parse(errorPage))
|
||||
var sanitizer = createBlueMondayPolicy()
|
||||
|
||||
type TemplateContext struct {
|
||||
StatusCode int
|
||||
StatusText string
|
||||
Message string
|
||||
}
|
||||
|
||||
// ReturnErrorPage sets the response status code and writes the error page to the response body.
|
||||
// The error page contains a sanitized version of the message and the statusCode both in text and numeric form.
|
||||
//
|
||||
// Currently, only the following html tags are supported: <code>
|
||||
func ReturnErrorPage(ctx *context.Context, msg string, statusCode int) {
|
||||
ctx.RespWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
ctx.RespWriter.WriteHeader(statusCode)
|
||||
|
||||
templateContext := TemplateContext{
|
||||
StatusCode: statusCode,
|
||||
StatusText: http.StatusText(statusCode),
|
||||
Message: sanitizer.Sanitize(msg),
|
||||
}
|
||||
|
||||
err := errorTemplate.Execute(ctx.RespWriter, templateContext)
|
||||
if err != nil {
|
||||
log.Err(err).Str("message", msg).Int("status", statusCode).Msg("could not write response")
|
||||
}
|
||||
}
|
||||
|
||||
func createBlueMondayPolicy() *bluemonday.Policy {
|
||||
p := bluemonday.NewPolicy()
|
||||
|
||||
p.AllowElements("code")
|
||||
|
||||
return p
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue