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

39 lines
1.1 KiB
Go
Raw Normal View History

2021-09-29 15:38:50 +00:00
package errorpage
import (
"github.com/valyala/fasthttp"
)
2021-10-06 17:38:00 +00:00
type (
errorsPager interface {
// GetPage with passed template name and error code.
GetPage(templateName, code string) ([]byte, error)
2021-09-29 15:38:50 +00:00
}
2021-10-06 17:38:00 +00:00
templatePicker interface {
// Pick the template name for responding.
Pick() string
2021-09-29 15:38:50 +00:00
}
2021-10-06 17:38:00 +00:00
)
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(e errorsPager, p templatePicker) fasthttp.RequestHandler {
2021-09-29 15:38:50 +00:00
return func(ctx *fasthttp.RequestCtx) {
2021-10-06 17:38:00 +00:00
ctx.SetContentType("text/plain; charset=utf-8") // default content type
2021-09-29 15:38:50 +00:00
if code, ok := ctx.UserValue("code").(string); ok {
2021-10-06 17:38:00 +00:00
if content, err := e.GetPage(p.Pick(), code); err == nil {
2021-09-29 15:38:50 +00:00
ctx.SetStatusCode(fasthttp.StatusOK)
ctx.SetContentType("text/html; charset=utf-8")
_, _ = ctx.Write(content)
} else {
2021-10-06 17:38:00 +00:00
ctx.SetStatusCode(fasthttp.StatusNotFound)
_, _ = ctx.WriteString("requested code not available: " + err.Error()) // TODO customize the output?
2021-09-29 15:38:50 +00:00
}
} else { // will never happen
2021-10-06 17:38:00 +00:00
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
_, _ = ctx.WriteString("cannot extract requested code from the request") // TODO customize the output?
2021-09-29 15:38:50 +00:00
}
}
}