gophertype/pkg/responses/errors.go

62 lines
1.9 KiB
Go

package responses
import (
"fmt"
"io"
"net/http"
"git.kirsle.net/apps/gophertype/pkg/console"
)
// Panic gives a simple error with no template or anything fancy.
func Panic(w io.Writer, code int, message string) {
if rw, ok := w.(http.ResponseWriter); ok {
rw.WriteHeader(code)
}
w.Write([]byte(message))
}
// Error returns an error page.
func Error(w http.ResponseWriter, r *http.Request, code int, message string) {
v := map[string]interface{}{
"Message": message,
}
w.WriteHeader(code)
if err := RenderTemplate(w, r, "_builtin/errors/generic.gohtml", v); err != nil {
console.Error("responses.Error: failed to render a pretty error template: %s", err)
w.Write([]byte(message))
}
}
// NotFound returns an HTML 404 page.
func NotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
if err := RenderTemplate(w, r, "_builtin/errors/404.gohtml", nil); err != nil {
console.Error("responses.NotFound: failed to render a pretty error template: %s", err)
Panic(w, http.StatusNotFound, "Not Found")
}
}
// BadRequest returns a 400 Bad Request page.
func BadRequest(w http.ResponseWriter, r *http.Request, vars interface{}) {
w.WriteHeader(http.StatusBadRequest)
if err := RenderTemplate(w, r, "_builtin/errors/400.gohtml", vars); err != nil {
console.Error("responses.BadRequest: failed to render a pretty error template: %s", err)
Panic(w, http.StatusBadRequest, "Bad Request")
}
}
// Forbidden returns a 403 Forbidden page.
func Forbidden(w http.ResponseWriter, r *http.Request, message string, args ...interface{}) {
w.WriteHeader(http.StatusForbidden)
v := NewTemplateVars(w, r)
v.Message = fmt.Sprintf(message, args...)
if err := RenderTemplate(w, r, "_builtin/errors/403.gohtml", v); err != nil {
console.Error("responses.Forbidden: failed to render a pretty error template: %s", err)
Panic(w, http.StatusForbidden, "Forbidden")
}
}