slightly less basic routing

This commit is contained in:
David 2022-05-27 19:34:48 -04:00
parent 364f98cbce
commit 0be3507b63
3 changed files with 41 additions and 8 deletions

41
main.go
View File

@ -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)

View File

@ -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:]

4
static/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
# Ignore all files in this dir...
*
# ... except for this one.
!.gitignore