xtablo-source/go-backend/router.go
2026-05-08 12:08:53 +02:00

56 lines
1.7 KiB
Go

package main
import (
"context"
"io/fs"
"net/http"
"os"
"xtablo-backend/internal/db"
"xtablo-backend/internal/web/handlers"
chi "github.com/go-chi/chi/v5"
)
func newRouter() http.Handler {
databaseURL := os.Getenv("DATABASE_URL")
repo, err := db.NewPostgresAuthRepository(context.Background(), databaseURL)
if err != nil {
panic(err)
}
return newRouterWithHandler(handlers.NewAuthHandler(repo))
}
func newTestRouter() http.Handler {
return newRouterWithHandler(handlers.NewAuthHandler(handlers.NewInMemoryAuthRepository()))
}
func newRouterWithHandler(authHandler *handlers.AuthHandler) http.Handler {
mux := chi.NewRouter()
staticFS := os.DirFS("static")
// Views
mux.Get("/", authHandler.GetHome())
mux.Get("/login", authHandler.GetLoginPage())
mux.Get("/signup", authHandler.GetSignupPage())
mux.Post("/login", authHandler.PostLogin())
mux.Post("/signup", authHandler.PostSignup())
mux.Post("/logout", authHandler.PostLogout())
mux.Handle("/static/*", http.StripPrefix("/static/", http.FileServerFS(os.DirFS("static"))))
mux.Handle("/pwa-icons/*", http.StripPrefix("/pwa-icons/", http.FileServerFS(os.DirFS("static/pwa-icons"))))
mux.HandleFunc("/logo_dark.png", serveStaticFile(staticFS, "logo_dark.png", "image/png"))
mux.HandleFunc("/logo_white.png", serveStaticFile(staticFS, "logo_white.png", "image/png"))
mux.HandleFunc("/manifest.webmanifest", serveStaticFile(staticFS, "manifest.webmanifest", "application/manifest+json"))
return mux
}
func serveStaticFile(fileSystem fs.FS, path string, contentType string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if contentType != "" {
w.Header().Set("Content-Type", contentType)
}
http.ServeFileFS(w, r, fileSystem, path)
}
}