alpha/main.go

80 lines
1.7 KiB
Go
Raw Normal View History

package main
2022-05-25 02:25:42 +00:00
import (
"log"
"net/http"
2022-05-27 23:34:48 +00:00
"strings"
2022-05-25 02:25:42 +00:00
"time"
)
type SessionProvider interface {
Create(user User, expr time.Duration) (string, error)
Get(key string) (User, error)
Refresh(key string, user User, expr time.Duration) error
}
type PageProvider interface {
Page(key string) (*Page, error)
Save(key string, page *Page) error
}
type RootHandler struct {
Sessions SessionProvider
Pages PageProvider
}
2022-05-27 23:34:48 +00:00
type AdminHandler struct {
Sessions SessionProvider
}
func (h *AdminHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("admin route"))
}
2022-05-25 02:25:42 +00:00
func (h *RootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2022-05-27 23:34:48 +00:00
if strings.HasPrefix(r.URL.Path, "/admin") {
(&AdminHandler{
Sessions: h.Sessions,
}).ServeHTTP(w, r)
2022-05-25 02:25:42 +00:00
return
}
2022-05-27 23:34:48 +00:00
// attempt to serve from the managed pages
2022-05-25 02:25:42 +00:00
page, err := h.Pages.Page(r.URL.Path)
2022-05-27 23:34:48 +00:00
if err == nil {
w.Write(page.Contents)
2022-05-25 02:25:42 +00:00
return
}
2022-05-27 23:34:48 +00:00
// 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)
2022-05-25 02:25:42 +00:00
}
func main() {
2022-05-25 02:25:42 +00:00
handler := &RootHandler{
Sessions: &Sessions{},
Pages: &Index{},
}
handler.Pages.Save("foo", &Page{
Contents: []byte("foobar"),
})
2022-05-27 23:34:48 +00:00
handler.Pages.Save("index", &Page{
Contents: []byte("root"),
})
2022-05-25 02:25:42 +00:00
err := http.ListenAndServe(":8080", handler)
log.Fatalf("server error: %v", err)
}