cheekylist/backend/main.go
2025-07-28 19:54:33 +02:00

83 lines
No EOL
2.3 KiB
Go

package main
import (
"embed"
"log"
"net/http"
"os"
"strconv"
"strings"
"gocheck/handlers"
"gocheck/static"
)
//go:embed all:frontend/dist
var staticFiles embed.FS
func main() {
// Ensure data directory exists
if err := os.MkdirAll("data", 0755); err != nil {
log.Fatalf("Failed to create data directory: %v", err)
}
// Start the lock expiry daemon
handlers.StartLockExpiryDaemon()
// Register API handlers first
http.HandleFunc("/api/checklists", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
handlers.HandleCreateChecklist(w, r)
} else {
http.NotFound(w, r)
}
})
http.HandleFunc("/api/checklists/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
log.Printf("API request: %s %s", r.Method, path)
switch {
case strings.HasSuffix(path, "/name") && r.Method == "PATCH":
log.Printf("Handling PATCH checklist name")
handlers.HandleUpdateChecklistName(w, r)
case strings.HasSuffix(path, "/items") && r.Method == "GET":
log.Printf("Handling GET items")
handlers.HandleGetItems(w, r)
case strings.HasSuffix(path, "/items") && r.Method == "POST":
log.Printf("Handling POST items")
handlers.HandleAddItem(w, r)
case strings.Contains(path, "/items/") && strings.HasSuffix(path, "/lock") && r.Method == "POST":
log.Printf("Handling lock item")
handlers.HandleLockItem(w, r)
case strings.Contains(path, "/items/") && r.Method == "PATCH":
log.Printf("Handling PATCH item")
handlers.HandleUpdateItem(w, r)
case strings.Contains(path, "/items/") && r.Method == "DELETE":
log.Printf("Handling DELETE item")
handlers.HandleDeleteItem(w, r)
case strings.HasSuffix(path, "/sse") && r.Method == "GET":
log.Printf("Handling SSE")
handlers.HandleSSE(w, r)
default:
log.Printf("No handler found for %s %s", r.Method, path)
http.NotFound(w, r)
}
})
// Serve static files from embedded filesystem (register last)
http.Handle("/", static.CompressionFileServer(staticFiles))
port := strings.TrimSpace(os.Getenv("PORT"))
if port == "" {
port = "8080"
}
parsedPort, err := strconv.Atoi(port)
if err != nil {
log.Fatalf("Invalid PORT environment variable: %v", err)
}
log.Printf("Listening on :%d", parsedPort)
log.Printf("Frontend available at: http://localhost:%d", parsedPort)
log.Fatal(http.ListenAndServe(":"+port, nil))
}