1
mirror of https://github.com/jlelse/GoBlog synced 2024-05-30 12:54:26 +00:00
GoBlog/errors.go

45 lines
1.3 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"net/http"
ct "github.com/elnormous/contenttype"
"go.goblog.app/app/pkgs/contenttype"
)
func (a *goBlog) serve404(w http.ResponseWriter, r *http.Request) {
2022-11-27 14:06:43 +00:00
a.serveError(w, r, fmt.Sprintf("%s was not found", r.URL.RequestURI()), http.StatusNotFound)
2020-12-24 09:09:34 +00:00
}
func (a *goBlog) serve410(w http.ResponseWriter, r *http.Request) {
2022-11-27 14:06:43 +00:00
a.serveError(w, r, fmt.Sprintf("%s doesn't exist anymore", r.URL.RequestURI()), http.StatusGone)
}
func (a *goBlog) serveNotAllowed(w http.ResponseWriter, r *http.Request) {
a.serveError(w, r, "", http.StatusMethodNotAllowed)
}
func (a *goBlog) serveError(w http.ResponseWriter, r *http.Request, message string, status int) {
2021-06-19 06:37:16 +00:00
// Init the first time
if len(a.errorCheckMediaTypes) == 0 {
a.errorCheckMediaTypes = append(a.errorCheckMediaTypes, ct.NewMediaType(contenttype.HTML))
2020-12-24 09:09:34 +00:00
}
2021-06-19 06:37:16 +00:00
// Check message
2020-12-24 09:09:34 +00:00
if message == "" {
message = http.StatusText(status)
}
2021-06-19 06:37:16 +00:00
// Check if request accepts HTML
if mt, _, err := ct.GetAcceptableMediaType(r, a.errorCheckMediaTypes); err != nil || mt.String() != a.errorCheckMediaTypes[0].String() {
// Request doesn't accept HTML
http.Error(w, message, status)
return
}
a.renderWithStatusCode(w, r, status, a.renderError, &renderData{
Data: &errorRenderData{
2021-06-19 06:37:16 +00:00
Title: fmt.Sprintf("%d %s", status, http.StatusText(status)),
2020-12-24 09:09:34 +00:00
Message: message,
2020-10-12 16:47:23 +00:00
},
})
}