hibiscus/serve.go

58 lines
1.7 KiB
Go
Raw Normal View History

2024-03-15 18:34:24 +03:00
package main
import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
2024-03-18 19:33:57 +03:00
"log"
2024-03-20 16:18:23 +03:00
"log/slog"
2024-03-15 18:34:24 +03:00
"net/http"
"strconv"
)
func Serve() {
r := chi.NewRouter()
r.Use(middleware.Logger, middleware.CleanPath, middleware.StripSlashes)
2024-03-26 14:00:32 +03:00
r.Use(BasicAuth) // Is this good enough? Sure hope so
2024-03-18 15:50:20 +03:00
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
http.ServeFile(w, r, "./pages/error/404.html")
})
2024-03-15 18:34:24 +03:00
// Home page
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./pages/index.html")
})
2024-03-26 14:32:19 +03:00
r.Get("/days", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./pages/days.html")
})
2024-03-15 18:34:24 +03:00
// API =============
apiRouter := chi.NewRouter()
2024-03-18 20:04:14 +03:00
apiRouter.Get("/readme", func(w http.ResponseWriter, r *http.Request) { GetFile("readme", w) })
2024-03-15 18:34:24 +03:00
apiRouter.Post("/readme", func(w http.ResponseWriter, r *http.Request) { PostFile("readme", w, r) })
2024-03-18 20:04:14 +03:00
apiRouter.Get("/log", func(w http.ResponseWriter, r *http.Request) { GetFile("log", w) })
2024-03-20 16:18:23 +03:00
apiRouter.Post("/log", PostLog)
2024-03-15 18:34:24 +03:00
2024-03-18 20:04:14 +03:00
apiRouter.Get("/day", func(w http.ResponseWriter, r *http.Request) { ListFiles("day", w) })
2024-03-20 16:18:23 +03:00
apiRouter.Get("/day/{day}", GetDay)
2024-03-15 18:34:24 +03:00
2024-03-18 20:04:14 +03:00
apiRouter.Get("/notes", func(w http.ResponseWriter, r *http.Request) { ListFiles("notes", w) })
2024-03-20 16:18:23 +03:00
apiRouter.Get("/notes/{note}", GetNote)
apiRouter.Post("/notes/{note}", PostNote)
2024-03-15 18:34:24 +03:00
2024-03-20 16:18:23 +03:00
apiRouter.Get("/today", GetToday)
apiRouter.Post("/today", PostToday)
2024-03-15 18:34:24 +03:00
2024-03-23 15:36:01 +03:00
apiRouter.Get("/export", GetExport)
2024-03-15 18:34:24 +03:00
r.Mount("/api", apiRouter)
// Static files
fs := http.FileServer(http.Dir("public"))
2024-03-18 20:04:14 +03:00
r.Handle("/public/*", http.StripPrefix("/public/", fs))
2024-03-15 18:34:24 +03:00
2024-03-20 16:18:23 +03:00
slog.Info("🌺 Website working", "port", Cfg.Port)
2024-03-18 19:33:57 +03:00
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(Cfg.Port), r))
2024-03-15 18:34:24 +03:00
}