GoBlog/errors.go

35 lines
729 B
Go
Raw Normal View History

package main
import (
"fmt"
"net/http"
2020-12-24 09:09:34 +00:00
"strings"
)
type errorData struct {
2020-09-21 14:12:17 +00:00
Title string
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)
}
func serveError(w http.ResponseWriter, r *http.Request, message string, status int) {
if !strings.Contains(strings.ToLower(r.Header.Get("Accept")), contentTypeHTML) {
http.Error(w, message, status)
return
}
title := fmt.Sprintf("%d %s", status, http.StatusText(status))
if message == "" {
message = http.StatusText(status)
}
2020-10-12 16:47:23 +00:00
render(w, templateError, &renderData{
Data: &errorData{
2020-12-24 09:09:34 +00:00
Title: title,
Message: message,
2020-10-12 16:47:23 +00:00
},
})
2020-12-24 09:09:34 +00:00
w.WriteHeader(status)
}