package main import ( "fmt" "net/http" "path/filepath" "strings" "github.com/gorilla/mux" "riedstra.dev/mitch/go-website/page" "riedstra.dev/mitch/go-website/rediscache" ) 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.HandleFunc("/login", a.LoginHandler) rtr.Handle("/logout", a.RequiresLogin(http.HandlerFunc(a.LogoutHandler))) rtr.PathPrefix("/edit/").Handler( a.RequiresLogin(http.StripPrefix("/edit/", http.HandlerFunc(a.EditPage)))).Methods("GET") rtr.PathPrefix("/edit/").Handler( a.RequiresLogin(http.StripPrefix("/edit/", http.HandlerFunc(a.SaveEditPage)))).Methods("POST") if a.redisPool != nil && !a.IsLoggedIn(r) { rtr.PathPrefix(fmt.Sprintf("/%s/{tag}", a.FeedPrefix)).Handler( rediscache.HandleWithParams(a.redisPool, a.RedisKey, http.HandlerFunc(a.FeedHandler))) rtr.PathPrefix("/").Handler(rediscache.Handle( a.redisPool, a.RedisKey, http.HandlerFunc(a.PageHandler))) } else { rtr.PathPrefix(fmt.Sprintf("/%s/{tag}", a.FeedPrefix)).HandlerFunc( a.FeedHandler) rtr.PathPrefix("/").Handler(http.HandlerFunc(a.PageHandler)) } rtr.ServeHTTP(w, r) } func (a *App) PageHandler(w http.ResponseWriter, r *http.Request) { u := r.URL.Path if u == "/" { u = "/index" } loggedIn := a.IsLoggedIn(r) if u == "/dashboard" && loggedIn { u = page.TemplateDirectory + "/dashboard" } // Render nothing inside of the template directory if we're not logged in if strings.HasPrefix(u[1:], filepath.Clean(page.TemplateDirectory)) && !loggedIn { page.Render4xx(w, r, map[string]interface{}{ "LoggedIn": loggedIn, }, 404) return } u = filepath.Join(".", u) page.RenderWithVars(w, r, u, map[string]interface{}{ "LoggedIn": loggedIn, }) } 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))) }