GoBlog/errors.go

50 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"net/http"
ct "github.com/elnormous/contenttype"
"go.goblog.app/app/pkgs/contenttype"
)
type errorData struct {
2020-09-21 14:12:17 +00:00
Title string
Message string
}
func (a *goBlog) serve404(w http.ResponseWriter, r *http.Request) {
a.serveError(w, r, fmt.Sprintf("%s was not found", r.RequestURI), http.StatusNotFound)
2020-12-24 09:09:34 +00:00
}
func (a *goBlog) serve410(w http.ResponseWriter, r *http.Request) {
a.serveError(w, r, fmt.Sprintf("%s doesn't exist anymore", r.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, templateError, &renderData{
2020-10-12 16:47:23 +00:00
Data: &errorData{
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
},
})
}