2021-10-06 17:38:00 +00:00
|
|
|
package index
|
|
|
|
|
|
|
|
import (
|
2022-01-27 12:29:49 +00:00
|
|
|
"strconv"
|
|
|
|
|
2021-10-06 17:38:00 +00:00
|
|
|
"github.com/valyala/fasthttp"
|
2023-02-23 17:49:45 +00:00
|
|
|
|
|
|
|
"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-10-06 17:38:00 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
templatePicker interface {
|
|
|
|
// Pick the template name for responding.
|
|
|
|
Pick() string
|
|
|
|
}
|
2022-01-31 08:43:40 +00:00
|
|
|
|
|
|
|
renderer interface {
|
|
|
|
Render(content []byte, props tpl.Properties) ([]byte, error)
|
|
|
|
}
|
2021-10-06 17:38:00 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// NewHandler creates handler for the index page serving.
|
2022-04-12 10:34:35 +00:00
|
|
|
func NewHandler(cfg *config.Config, p templatePicker, rdr renderer, opt options.ErrorPage) fasthttp.RequestHandler {
|
2021-10-06 17:38:00 +00:00
|
|
|
return func(ctx *fasthttp.RequestCtx) {
|
2022-04-12 10:34:35 +00:00
|
|
|
pageCode, httpCode := opt.Default.PageCode, int(opt.Default.HTTPCode)
|
2021-10-06 17:38:00 +00:00
|
|
|
|
2022-01-27 12:29:49 +00:00
|
|
|
if returnCode, ok := extractCodeToReturn(ctx); ok {
|
|
|
|
pageCode, httpCode = strconv.Itoa(returnCode), returnCode
|
2021-10-06 17:38:00 +00:00
|
|
|
}
|
|
|
|
|
2022-04-12 10:34:35 +00:00
|
|
|
core.RespondWithErrorPage(ctx, cfg, p, rdr, pageCode, httpCode, opt)
|
2022-01-27 12:29:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func extractCodeToReturn(ctx *fasthttp.RequestCtx) (int, bool) { // for the Ingress support
|
|
|
|
var ch = ctx.Request.Header.Peek(core.CodeHeader)
|
|
|
|
|
|
|
|
if len(ch) > 0 && len(ch) <= 3 {
|
|
|
|
if code, err := strconv.Atoi(string(ch)); err == nil {
|
|
|
|
if code > 0 && code <= 599 {
|
|
|
|
return code, true
|
|
|
|
}
|
|
|
|
}
|
2021-10-06 17:38:00 +00:00
|
|
|
}
|
2022-01-27 12:29:49 +00:00
|
|
|
|
|
|
|
return 0, false
|
2021-10-06 17:38:00 +00:00
|
|
|
}
|