CUB-182: Chi router setup with auth middleware and graceful shutdown

This commit is contained in:
2026-05-18 17:47:06 -04:00
parent c0b2b4cf57
commit 7a0a76bbd5
5 changed files with 68 additions and 8 deletions
+65 -7
View File
@@ -2,11 +2,20 @@
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/cubecraft/remoterig/internal/auth"
"github.com/cubecraft/remoterig/internal/db"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"gopkg.in/yaml.v3"
)
@@ -37,14 +46,63 @@ func main() {
log.Fatalf("Failed to load config: %v", err)
}
// Print config values
log.Printf("Database: %s", cfg.DBPath)
log.Printf("API key set: %t", cfg.APIKey != "")
log.Printf("Server port: %s", cfg.Port)
log.Printf("MQTT broker: %s", cfg.MQTT.Broker)
log.Printf("Platform: %s (max %d cameras)", cfg.Platform.Type, cfg.Platform.MaxCameras)
// Open database
db, err := db.Open(cfg.DBPath)
if err != nil {
log.Fatalf("Failed to open database: %v", err)
}
defer db.Close()
log.Printf("Database open: %s", cfg.DBPath)
log.Println("RemoteRig hub ready")
// Set up router
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(cfg.WriteTimeout))
// Health check (no auth)
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
})
// API routes (auth required if API key is configured)
r.Mount("/api/v1", auth.Middleware(cfg.APIKey)(apiRouter(db)))
// Create server
httpServer := &http.Server{
Addr: ":" + cfg.Port,
Handler: r,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
IdleTimeout: cfg.IdleTimeout,
}
// Graceful shutdown
go func() {
sigInt := make(chan os.Signal, 1)
signal.Notify(sigInt, syscall.SIGINT, syscall.SIGTERM)
<-sigInt
log.Println("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
httpServer.Shutdown(ctx)
}()
log.Printf("Server listening on port %s", cfg.Port)
if err := httpServer.ListenAndServe(); err != nil {
log.Fatalf("Server failed: %v", err)
}
}
// apiRouter creates the API route tree.
func apiRouter(database *db.DB) http.Handler {
r := chi.NewRouter()
// TODO: register handler routes here
// Example: r.Get("/cameras", handlers.ListCameras(database))
return r
}
func loadConfig(path string) (*Config, error) {