This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/handler/default.go
Tim Wundenberg e53a0e5cf7
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 49s
chore(auth): add service structs and test error handling
2024-09-20 22:19:02 +02:00

72 lines
1.9 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/"))))
authHandler := AuthHandler{
db: db,
service: service.NewAuthService(db),
}
router.Handle("/auth/", authHandler.authUi())
router.Handle("/api/auth/", authHandler.authApi())
router.Handle("/workout", authMiddleware(db, workoutUi(db)))
router.Handle("/api/workout", authMiddleware(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/", authMiddleware(db, workoutApi(db)))
return middleware.Logging(
middleware.EnableCors(
router))
}
func authMiddleware(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)
}
}