pages-server/html/error.go
2022-08-28 20:54:17 +02:00

43 lines
1 KiB
Go

package html
import (
"io"
"net/http"
"strconv"
"strings"
"codeberg.org/codeberg/pages/server/context"
)
// ReturnErrorPage sets the response status code and writes NotFoundPage to the response body, with "%status" replaced
// with the provided status code.
func ReturnErrorPage(ctx *context.Context, msg string, code int) {
ctx.RespWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx.RespWriter.WriteHeader(code)
if msg == "" {
msg = errorBody(code)
}
_, _ = io.Copy(ctx.RespWriter, strings.NewReader(msg))
}
func errorMessage(statusCode int) string {
message := http.StatusText(statusCode)
switch statusCode {
case http.StatusMisdirectedRequest:
message += " - domain not specified in <code>.domains</code> file"
case http.StatusFailedDependency:
message += " - target repo/branch doesn't exist or is private"
}
return message
}
// TODO: use template engine?
func errorBody(statusCode int) string {
return strings.ReplaceAll(NotFoundPage,
"%status",
strconv.Itoa(statusCode)+" "+errorMessage(statusCode))
}