package main import ( "net/http" "path/filepath" "strings" "fmt" "riedstra.dev/mitch/go-website/mapcache" "riedstra.dev/mitch/go-website/page" "riedstra.dev/mitch/go-website/rediscache" ) func (a *App) Handler() http.Handler { mux := http.NewServeMux() type route struct { path string handler http.Handler } routes := []route{ {a.ReIndexPath, a.RebuildIndexHandler()}, {"/static/", a.StaticHandler()}, } cacheableRoutes := []route{ {a.FeedPrefix, http.StripPrefix(a.FeedPrefix, a.FeedHandler())}, {"/", a.PageHandler()}, } for _, route := range routes { mux.Handle(route.path, route.handler) } if a.cache == nil && a.RedisKey != "" { a.cache = mapcache.New() } var cacheHandler func(http.Handler) http.Handler = nil switch { case a.mapCache: cacheHandler = a.cache.Handle case a.redisPool != nil: cacheHandler = func(h http.Handler) http.Handler { return rediscache.Handle(a.redisPool, a.RedisKey, h) } default: // No caching middleware cacheHandler = func(h http.Handler) http.Handler { return h } } if cacheHandler == nil { panic("cacheHandler cannot be nil") } for _, r := range cacheableRoutes { fmt.Printf("Calling mux.Handle(r.path(%s), cacheHandler(r.handler(%v)))\n", r.path, r.handler) mux.Handle(r.path, cacheHandler(r.handler)) } return mux } func (a *App) PageHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { u := page.GetURLPath(r) // Render nothing inside of the template directory if strings.HasPrefix(u[1:], filepath.Clean(page.TemplateDirectory)) { return } u = filepath.Join(".", u) page.RenderWithVars(w, r, u, map[string]interface{}{}) }) } func (a *App) RebuildIndexHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { u := page.GetPagePath(r) 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))) }