mirror of
https://github.com/tarampampam/error-pages.git
synced 2024-08-30 18:22:40 +00:00
50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package index
|
|
|
|
import (
|
|
"strconv"
|
|
|
|
"github.com/tarampampam/error-pages/internal/config"
|
|
"github.com/tarampampam/error-pages/internal/http/core"
|
|
"github.com/tarampampam/error-pages/internal/options"
|
|
"github.com/tarampampam/error-pages/internal/tpl"
|
|
"github.com/valyala/fasthttp"
|
|
)
|
|
|
|
type (
|
|
templatePicker interface {
|
|
// Pick the template name for responding.
|
|
Pick() string
|
|
}
|
|
|
|
renderer interface {
|
|
Render(content []byte, props tpl.Properties) ([]byte, error)
|
|
}
|
|
)
|
|
|
|
// NewHandler creates handler for the index page serving.
|
|
func NewHandler(cfg *config.Config, p templatePicker, rdr renderer, opt options.ErrorPage) fasthttp.RequestHandler {
|
|
return func(ctx *fasthttp.RequestCtx) {
|
|
pageCode, httpCode := opt.Default.PageCode, int(opt.Default.HTTPCode)
|
|
|
|
if returnCode, ok := extractCodeToReturn(ctx); ok {
|
|
pageCode, httpCode = strconv.Itoa(returnCode), returnCode
|
|
}
|
|
|
|
core.RespondWithErrorPage(ctx, cfg, p, rdr, pageCode, httpCode, opt)
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
}
|
|
|
|
return 0, false
|
|
}
|