82 lines
2.3 KiB
Go
82 lines
2.3 KiB
Go
package server
|
|
|
|
import (
|
|
"embed"
|
|
"net/http"
|
|
|
|
"git.bronku.xyz/bronku/cake-order-tracker/logging"
|
|
"git.bronku.xyz/bronku/cake-order-tracker/server/templates"
|
|
"git.bronku.xyz/bronku/cake-order-tracker/store"
|
|
"github.com/a-h/templ"
|
|
)
|
|
|
|
type httpError struct {
|
|
code int
|
|
error
|
|
}
|
|
|
|
type fetcher[T any] func(r *http.Request) (T, *httpError)
|
|
type templateBuilder[T any] func(data T) templ.Component
|
|
|
|
func render[T any](title string, fetch fetcher[T], builder templateBuilder[T]) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
data, fetchErr := fetch(r)
|
|
if fetchErr != nil {
|
|
logging.ErrorPage(fetchErr, fetchErr.code).ServeHTTP(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("content-type", "text/html")
|
|
|
|
var component templ.Component
|
|
if r.Header.Get("HX-Request") == "true" {
|
|
component = templates.MainContent(title, builder(data))
|
|
} else {
|
|
component = templates.Layout(title, builder(data))
|
|
}
|
|
|
|
err := component.Render(r.Context(), w)
|
|
if err != nil {
|
|
logging.ErrorPage(err, http.StatusInternalServerError).ServeHTTP(w, r)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
type Server struct {
|
|
s *store.Store
|
|
http.Handler
|
|
}
|
|
|
|
//go:embed static/*
|
|
var static embed.FS
|
|
|
|
func redirect(path string, code int) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
http.Redirect(w, r, path, code)
|
|
}
|
|
}
|
|
|
|
func New(store *store.Store) *Server {
|
|
var server Server
|
|
server.s = store
|
|
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /", redirect("/orders", http.StatusSeeOther))
|
|
mux.HandleFunc("GET /order", render("Nowe zamówienie", server.newOrder, templates.OrderForm))
|
|
mux.HandleFunc("GET /order/{id}", render("Zamówienie", server.order, templates.OrderForm))
|
|
// mux.HandleFunc("GET /orders", render(server.orders))
|
|
// mux.HandleFunc("GET /cake", render(server.cake))
|
|
// mux.HandleFunc("GET /cakes", render(server.cakes))
|
|
// mux.HandleFunc("POST /order", render(server.postOrder))
|
|
// mux.HandleFunc("POST /order/{id}/status", render(server.updateStatus))
|
|
// mux.HandleFunc("POST /cake", render(server.postCake))
|
|
// mux.HandleFunc("GET /blocked", render(server.blocked))
|
|
// mux.HandleFunc("POST /blocked", render(server.postBlocked))
|
|
// mux.HandleFunc("POST /blocked/{id}/delete", render(server.deleteBlocked))
|
|
|
|
fs := http.FileServerFS(static)
|
|
mux.Handle("GET /static/", fs)
|
|
|
|
server.Handler = mux
|
|
return &server
|
|
}
|