2024-11-05 12:17:27 +00:00
|
|
|
package routes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log/slog"
|
|
|
|
"net/http"
|
|
|
|
|
2024-11-17 01:21:51 +00:00
|
|
|
"git.codemonkeysoftware.net/b/peachy-go"
|
2024-11-05 12:17:27 +00:00
|
|
|
"git.codemonkeysoftware.net/b/peachy-go/desktop/components"
|
2024-11-17 01:21:51 +00:00
|
|
|
"git.codemonkeysoftware.net/b/peachy-go/desktop/fields"
|
2024-11-05 12:17:27 +00:00
|
|
|
"git.codemonkeysoftware.net/b/peachy-go/desktop/pages"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
|
|
"github.com/go-chi/httplog/v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
Create a new chi router, configure it and return it.
|
|
|
|
*/
|
2024-11-17 01:21:51 +00:00
|
|
|
func NewChiRouter(port string, db *peachy.DB) *chi.Mux {
|
2024-11-05 12:17:27 +00:00
|
|
|
|
|
|
|
r := chi.NewRouter()
|
|
|
|
|
|
|
|
logger := httplog.NewLogger("app-logger", httplog.Options{
|
|
|
|
LogLevel: slog.LevelInfo,
|
|
|
|
Concise: true,
|
|
|
|
})
|
|
|
|
|
|
|
|
// Use the logger and recoverer middleware.
|
|
|
|
r.Use(httplog.RequestLogger(logger))
|
|
|
|
r.Use(middleware.Recoverer)
|
|
|
|
|
|
|
|
/*
|
|
|
|
// ULTRA IMPORTANT : This middleware is used to prevent caching of the pages.
|
|
|
|
// Sometimes, HX requests may be cached by the browser, which may cause unexpected behavior.
|
|
|
|
r.Use(func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
*/
|
|
|
|
|
|
|
|
r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
|
|
|
|
|
2024-11-17 01:21:51 +00:00
|
|
|
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
2024-11-15 18:55:31 +00:00
|
|
|
HXRender(w, r, pages.Splash)
|
|
|
|
})
|
|
|
|
|
2024-11-17 01:21:51 +00:00
|
|
|
r.Get("/site", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
page, err := pages.HomePage(db)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("internal error", "path", r.URL.Path, "error", err)
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
HXRender(w, r, page)
|
|
|
|
})
|
|
|
|
|
|
|
|
r.Patch("/site", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
r.ParseForm()
|
|
|
|
if r.Form.Has(fields.SiteName) {
|
|
|
|
err := db.SetSiteName(r.Form.Get(fields.SiteName))
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("internal error", "path", r.URL.Path, "error", err)
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
w.WriteHeader(http.StatusOK)
|
2024-11-05 12:17:27 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
HXRender(w, r, components.HelloWorld)
|
|
|
|
})
|
|
|
|
|
2024-11-15 18:55:31 +00:00
|
|
|
go http.ListenAndServe(":"+port, r)
|
2024-11-05 12:17:27 +00:00
|
|
|
|
|
|
|
return r
|
|
|
|
}
|