Handle 404

This commit is contained in:
Joakim Hellsén 2024-02-03 19:03:40 +01:00
commit cf726c800e
2 changed files with 36 additions and 1 deletions

18
main.go
View file

@ -26,6 +26,8 @@ func main() {
r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
r.NotFound(NotFoundHandler)
log.Println("Listening on http://localhost:8000/ <Ctrl-C> to stop") log.Println("Listening on http://localhost:8000/ <Ctrl-C> to stop")
http.ListenAndServe("127.0.0.1:8000", r) http.ListenAndServe("127.0.0.1:8000", r)
} }
@ -38,6 +40,7 @@ type Data struct {
CanonicalURL string CanonicalURL string
FeedCount int FeedCount int
DatabaseSize int DatabaseSize int
Request *http.Request
} }
func (d *Data) GetDatabaseSizeAndFeedCount() { func (d *Data) GetDatabaseSizeAndFeedCount() {
@ -68,9 +71,22 @@ func renderPage(w http.ResponseWriter, title, description, keywords, author, url
t.ExecuteTemplate(w, "base", data) t.ExecuteTemplate(w, "base", data)
} }
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
data := Data{
Request: r,
}
data.GetDatabaseSizeAndFeedCount()
t, err := template.ParseFiles("templates/base.tmpl", "templates/404.tmpl")
if err != nil {
http.Error(w, fmt.Sprintf("Internal Server Error: %v", err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNotFound)
t.ExecuteTemplate(w, "base", data)
}
func IndexHandler(w http.ResponseWriter, _ *http.Request) { func IndexHandler(w http.ResponseWriter, _ *http.Request) {
renderPage(w, "FeedVault", "FeedVault - A feed archive", "RSS, Atom, Feed, Archive", "TheLovinator", "http://localhost:8000/", "index") renderPage(w, "FeedVault", "FeedVault - A feed archive", "RSS, Atom, Feed, Archive", "TheLovinator", "http://localhost:8000/", "index")
} }
func ApiHandler(w http.ResponseWriter, _ *http.Request) { func ApiHandler(w http.ResponseWriter, _ *http.Request) {

19
templates/404.tmpl Normal file
View file

@ -0,0 +1,19 @@
{{ define "content" }}
<span style="text-align: center;">
<h2>404 - Page not found</h2>
<p>Sorry, the page you are looking for does not exist.</p>
</span>
<p>
Extra information:
<ul>
<li>Host: {{ .Request.Host }}</li>
<li>Method: {{ .Request.Method }}</li>
<li>Proto: {{ .Request.Proto }}</li>
<li>RemoteAddr: {{ .Request.RemoteAddr }}</li>
<li>RequestURI: {{ .Request.RequestURI }}</li>
<li>URL: {{ .Request.URL }}</li>
<li>UserAgent: {{ .Request.UserAgent }}</li>
</ul>
{{ end }}