error-pages/internal/http/handlers/errorpage/handler.go

36 lines
1.0 KiB
Go
Raw Normal View History

2021-09-29 15:38:50 +00:00
package errorpage
import (
"github.com/valyala/fasthttp"
"gh.tarampamp.am/error-pages/internal/config"
"gh.tarampamp.am/error-pages/internal/http/core"
"gh.tarampamp.am/error-pages/internal/options"
"gh.tarampamp.am/error-pages/internal/tpl"
2021-09-29 15:38:50 +00:00
)
type (
templatePicker interface {
// Pick the template name for responding.
Pick() string
}
renderer interface {
Render(content []byte, props tpl.Properties) ([]byte, error)
}
)
2021-09-29 15:38:50 +00:00
2021-10-06 17:38:00 +00:00
// NewHandler creates handler for error pages serving.
func NewHandler(cfg *config.Config, p templatePicker, rdr renderer, opt options.ErrorPage) fasthttp.RequestHandler {
2021-09-29 15:38:50 +00:00
return func(ctx *fasthttp.RequestCtx) {
core.SetClientFormat(ctx, core.PlainTextContentType) // default content type
2021-09-29 15:38:50 +00:00
if code, ok := ctx.UserValue("code").(string); ok {
core.RespondWithErrorPage(ctx, cfg, p, rdr, code, fasthttp.StatusOK, opt)
} else { // will never occur
2021-10-06 17:38:00 +00:00
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
_, _ = ctx.WriteString("cannot extract requested code from the request")
2021-09-29 15:38:50 +00:00
}
}
}