All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 46s
67 lines
1.7 KiB
Go
67 lines
1.7 KiB
Go
package handler
|
|
|
|
import (
|
|
"me-fit/middleware"
|
|
"me-fit/service"
|
|
"me-fit/template"
|
|
"me-fit/utils"
|
|
|
|
"database/sql"
|
|
"net/http"
|
|
)
|
|
|
|
func GetHandler(db *sql.DB) http.Handler {
|
|
router := http.NewServeMux()
|
|
|
|
router.HandleFunc("/$", handleIndex(db))
|
|
router.HandleFunc("/", handleNotFound(db))
|
|
|
|
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
|
|
|
router.Handle("/auth/", authUi(db))
|
|
router.Handle("/api/auth/", authApi(db))
|
|
|
|
router.Handle("/workout", auth(db, workoutUi(db)))
|
|
router.Handle("/api/workout", auth(db, workoutApi(db)))
|
|
// Needed a second time with trailing slash, otherwise either /api/workout or /api/workout/{id} does not match
|
|
router.Handle("/api/workout/", auth(db, workoutApi(db)))
|
|
|
|
return middleware.Logging(
|
|
middleware.EnableCors(
|
|
router))
|
|
}
|
|
|
|
func auth(db *sql.DB, h http.Handler) http.Handler {
|
|
return middleware.EnsureValidSession(db, h)
|
|
}
|
|
|
|
func handleIndex(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user := service.GetUserFromRequest(db, r)
|
|
|
|
err := template.
|
|
Layout(template.Index(), service.UserInfoComp(user)).
|
|
Render(r.Context(), w)
|
|
if err != nil {
|
|
utils.LogError("Failed to render index", err)
|
|
http.Error(w, "Failed to render index", http.StatusInternalServerError)
|
|
}
|
|
}
|
|
}
|
|
|
|
func handleNotFound(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user := service.GetUserFromRequest(db, r)
|
|
|
|
err := template.
|
|
Layout(template.NotFound(), service.UserInfoComp(user)).
|
|
Render(r.Context(), w)
|
|
if err != nil {
|
|
utils.LogError("Failed to render index", err)
|
|
http.Error(w, "Failed to render index", http.StatusInternalServerError)
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}
|