2021-12-05 13:47:33 +00:00
|
|
|
package html
|
|
|
|
|
|
|
|
import (
|
2022-07-15 16:10:41 +00:00
|
|
|
"net/http"
|
2021-12-05 13:47:33 +00:00
|
|
|
"strconv"
|
2022-08-28 14:21:37 +00:00
|
|
|
"strings"
|
2022-08-28 18:54:17 +00:00
|
|
|
|
|
|
|
"codeberg.org/codeberg/pages/server/context"
|
2021-12-05 13:47:33 +00:00
|
|
|
)
|
|
|
|
|
2022-11-11 23:05:51 +00:00
|
|
|
// ReturnErrorPage sets the response status code and writes NotFoundPage to the response body,
|
|
|
|
// with "%status%" and %message% replaced with the provided statusCode and msg
|
2022-11-07 22:37:52 +00:00
|
|
|
func ReturnErrorPage(ctx *context.Context, msg string, statusCode int) {
|
2022-08-28 18:54:17 +00:00
|
|
|
ctx.RespWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
|
2022-11-07 22:37:52 +00:00
|
|
|
ctx.RespWriter.WriteHeader(statusCode)
|
2022-08-28 18:54:17 +00:00
|
|
|
|
|
|
|
if msg == "" {
|
2022-11-07 22:37:52 +00:00
|
|
|
msg = errorBody(statusCode)
|
|
|
|
} else {
|
|
|
|
// TODO: use template engine
|
|
|
|
msg = strings.ReplaceAll(strings.ReplaceAll(ErrorPage, "%message%", msg), "%status%", http.StatusText(statusCode))
|
2022-08-28 18:54:17 +00:00
|
|
|
}
|
|
|
|
|
2022-11-11 23:40:18 +00:00
|
|
|
_, _ = ctx.RespWriter.Write([]byte(msg))
|
2022-08-28 18:54:17 +00:00
|
|
|
}
|
|
|
|
|
2022-07-15 16:10:41 +00:00
|
|
|
func errorMessage(statusCode int) string {
|
|
|
|
message := http.StatusText(statusCode)
|
|
|
|
|
|
|
|
switch statusCode {
|
|
|
|
case http.StatusMisdirectedRequest:
|
2021-12-05 13:47:33 +00:00
|
|
|
message += " - domain not specified in <code>.domains</code> file"
|
2022-07-15 16:10:41 +00:00
|
|
|
case http.StatusFailedDependency:
|
2021-12-05 13:47:33 +00:00
|
|
|
message += " - target repo/branch doesn't exist or is private"
|
|
|
|
}
|
2022-07-15 16:10:41 +00:00
|
|
|
|
|
|
|
return message
|
|
|
|
}
|
|
|
|
|
2022-11-07 22:37:52 +00:00
|
|
|
// TODO: use template engine
|
2022-08-28 14:21:37 +00:00
|
|
|
func errorBody(statusCode int) string {
|
|
|
|
return strings.ReplaceAll(NotFoundPage,
|
2022-11-07 22:37:52 +00:00
|
|
|
"%status%",
|
2022-08-28 14:21:37 +00:00
|
|
|
strconv.Itoa(statusCode)+" "+errorMessage(statusCode))
|
2021-12-05 13:47:33 +00:00
|
|
|
}
|