aboutsummaryrefslogtreecommitdiff
path: root/cmd/server/handlers.go
diff options
context:
space:
mode:
Diffstat (limited to 'cmd/server/handlers.go')
-rw-r--r--cmd/server/handlers.go53
1 files changed, 53 insertions, 0 deletions
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)
+}