2020-07-31 19:02:47 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2021-03-10 10:29:20 +00:00
|
|
|
|
|
|
|
"github.com/elnormous/contenttype"
|
2020-07-31 19:02:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type errorData struct {
|
2020-09-21 14:12:17 +00:00
|
|
|
Title string
|
2020-07-31 19:02:47 +00:00
|
|
|
Message string
|
|
|
|
}
|
|
|
|
|
2020-09-21 14:12:17 +00:00
|
|
|
func serve404(w http.ResponseWriter, r *http.Request) {
|
2020-12-24 09:09:34 +00:00
|
|
|
serveError(w, r, fmt.Sprintf("%s was not found", r.RequestURI), http.StatusNotFound)
|
|
|
|
}
|
|
|
|
|
2021-03-22 14:57:29 +00:00
|
|
|
func serveNotAllowed(w http.ResponseWriter, r *http.Request) {
|
|
|
|
serveError(w, r, "", http.StatusMethodNotAllowed)
|
|
|
|
}
|
|
|
|
|
2021-03-10 10:29:20 +00:00
|
|
|
var errorCheckMediaTypes = []contenttype.MediaType{
|
|
|
|
contenttype.NewMediaType(contentTypeHTML),
|
|
|
|
}
|
|
|
|
|
2020-12-24 09:09:34 +00:00
|
|
|
func serveError(w http.ResponseWriter, r *http.Request, message string, status int) {
|
2021-03-10 10:29:20 +00:00
|
|
|
if mt, _, err := contenttype.GetAcceptableMediaType(r, errorCheckMediaTypes); err != nil || mt.String() != errorCheckMediaTypes[0].String() {
|
|
|
|
// Request doesn't accept HTML
|
2020-12-24 09:09:34 +00:00
|
|
|
http.Error(w, message, status)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
title := fmt.Sprintf("%d %s", status, http.StatusText(status))
|
|
|
|
if message == "" {
|
|
|
|
message = http.StatusText(status)
|
|
|
|
}
|
2021-03-09 20:48:30 +00:00
|
|
|
w.WriteHeader(status)
|
2021-02-20 22:35:16 +00:00
|
|
|
render(w, r, templateError, &renderData{
|
2020-10-12 16:47:23 +00:00
|
|
|
Data: &errorData{
|
2020-12-24 09:09:34 +00:00
|
|
|
Title: title,
|
|
|
|
Message: message,
|
2020-10-12 16:47:23 +00:00
|
|
|
},
|
2020-07-31 19:02:47 +00:00
|
|
|
})
|
|
|
|
}
|