feat: fileserver + logging + styling

This commit is contained in:
2025-05-18 17:00:07 +02:00
parent f382ccc008
commit fa30f66b6b
8 changed files with 160 additions and 31 deletions

View File

@ -4,10 +4,13 @@ import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"gitea.local/admin/hspguard/internal/repository"
"gitea.local/admin/hspguard/internal/user"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
type APIServer struct {
@ -24,6 +27,11 @@ func NewAPIServer(addr string, db *repository.Queries) *APIServer {
func (s *APIServer) Run() error {
router := chi.NewRouter()
router.Use(middleware.Logger)
workDir, _ := os.Getwd()
staticDir := http.Dir(filepath.Join(workDir, "static"))
FileServer(router, "/static", staticDir)
router.Route("/api/v1", func(r chi.Router) {
userHandler := user.NewUserHandler()

View File

@ -0,0 +1,28 @@
package api
import (
"net/http"
"strings"
"github.com/go-chi/chi/v5"
)
func FileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit any URL parameters.")
}
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
fs := http.StripPrefix(pathPrefix, http.FileServer(root))
fs.ServeHTTP(w, r)
})
}