From e6d53f71c9718ecdb9fde16a924d75a71aadd2d2 Mon Sep 17 00:00:00 2001 From: Mitchell Riedstra Date: Wed, 7 Jul 2021 15:39:51 -0400 Subject: Add the handler file that was accidently ignored --- cmd/server/handlers.go | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 cmd/server/handlers.go (limited to 'cmd/server') diff --git a/cmd/server/handlers.go b/cmd/server/handlers.go new file mode 100644 index 0000000..60e0a35 --- /dev/null +++ b/cmd/server/handlers.go @@ -0,0 +1,53 @@ +package main + +import ( + "net/http" + "path/filepath" + + "github.com/gorilla/mux" + "riedstra.dev/mitch/go-website/page" +) + +type App struct { + ReIndexPath string + StaticDirectory string +} + +func (a *App) PageHandler(w http.ResponseWriter, r *http.Request) { + u := r.URL.Path + if u == "/" { + u = "/index" + } + u = filepath.Join(".", u) + + page.RenderForPath(w, r, u) +} + +func (a *App) RebuildIndexHandler(w http.ResponseWriter, r *http.Request) { + u := r.URL.Path + if u == "/" { + u = "/index" + } + u = filepath.Join(".", u) + + p := page.NewPage("index") + err := p.RebuildIndex() + + page.RenderWithVars(w, r, u, map[string]interface{}{ + "IndexError": err, + }) +} + +// StaticHandler simply returns a HTTP handler that looks at the current +// directory and exposes `static` via HTTP `/static` +func (a *App) StaticHandler() http.Handler { + return http.StripPrefix("/static/", http.FileServer(http.Dir(a.StaticDirectory))) +} + +func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) { + rtr := mux.NewRouter() + rtr.HandleFunc(a.ReIndexPath, a.RebuildIndexHandler) + rtr.PathPrefix("/static/").Handler(a.StaticHandler()) + rtr.PathPrefix("/").HandlerFunc(a.PageHandler) + rtr.ServeHTTP(w, r) +} -- cgit v1.2.3