diff --git a/main.go b/main.go index a1e9f35..9e9420b 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "log" "net/http" + "strings" "time" ) @@ -22,18 +23,43 @@ type RootHandler struct { Pages PageProvider } +type AdminHandler struct { + Sessions SessionProvider +} + +func (h *AdminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("admin route")) +} + func (h *RootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/admin" { - w.Write([]byte("admin route")) + if strings.HasPrefix(r.URL.Path, "/admin") { + (&AdminHandler{ + Sessions: h.Sessions, + }).ServeHTTP(w, r) return } + // attempt to serve from the managed pages page, err := h.Pages.Page(r.URL.Path) - if err == ErrPageNotFound { - w.WriteHeader(http.StatusNotFound) - w.Write([]byte("not found")) + if err == nil { + w.Write(page.Contents) return } - w.Write(page.Contents) + // fall back to serving out of the static directory, but: + // 1. prevent the generated indexes from rendering + if strings.HasSuffix(r.URL.Path, "/") { + http.NotFound(w, r) + return + } + // 2. prevent hidden paths from rendering + for _, seg := range strings.Split(r.URL.Path, "/") { + if strings.HasPrefix(seg, ".") { + http.NotFound(w, r) + return + } + } + // finally, use the built-in fileserver to serve + fs := http.FileServer(http.Dir("./static")) + fs.ServeHTTP(w, r) } func main() { @@ -44,6 +70,9 @@ func main() { handler.Pages.Save("foo", &Page{ Contents: []byte("foobar"), }) + handler.Pages.Save("index", &Page{ + Contents: []byte("root"), + }) err := http.ListenAndServe(":8080", handler) log.Fatalf("server error: %v", err) diff --git a/model.go b/model.go index 6a69798..c51b284 100644 --- a/model.go +++ b/model.go @@ -59,11 +59,11 @@ func (i *Index) Page(key string) (*Page, error) { // overwriting any that may have existed before. // `foo/` is stored as a page named 'foo' in the current index; // default 'index' files should be explicitly passed as such. -// The empty key or `/` are invalid and result in an error. +// The empty key or `/` are turned into the "index" key. // Leading slashes are stripped. func (i *Index) Save(key string, page *Page) error { if key == "" || key == "/" { - return fmt.Errorf("invalid page key") + key = "index" } if key[0] == '/' { // strip leading slash key = key[1:] diff --git a/static/.gitignore b/static/.gitignore new file mode 100644 index 0000000..2191032 --- /dev/null +++ b/static/.gitignore @@ -0,0 +1,4 @@ +# Ignore all files in this dir... +* +# ... except for this one. +!.gitignore \ No newline at end of file