Implemented Epic 1 core kernel and infrastructure stories: Story 1.1: Enhanced DI Container - Added providers for database, health, metrics, and error bus - Extended CoreModule to include all core services Story 1.2: Database Layer with Ent ORM - Created Ent schema for User, Role, Permission, AuditLog entities - Implemented many-to-many relationships (User-Role, Role-Permission) - Created database client wrapper with connection pooling - Added database provider to DI container with migration support Story 1.3: Health Monitoring and Metrics System - Implemented health check registry and interface - Added database health checker - Created Prometheus metrics system with HTTP instrumentation - Added health and metrics providers to DI container Story 1.4: Error Handling and Error Bus - Implemented channel-based error bus - Created ErrorPublisher interface - Added error bus provider with lifecycle management Story 1.5: HTTP Server Foundation - Created HTTP server with Gin framework - Implemented comprehensive middleware stack: - Request ID generation - Structured logging - Panic recovery with error bus integration - Prometheus metrics collection - CORS support - Registered core routes: /healthz, /ready, /metrics - Integrated with FX lifecycle for graceful shutdown All components are integrated via DI container and ready for use.
132 lines
3.1 KiB
Go
132 lines
3.1 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"git.dcentral.systems/toolz/goplt/internal/health"
|
|
"git.dcentral.systems/toolz/goplt/internal/metrics"
|
|
"git.dcentral.systems/toolz/goplt/pkg/config"
|
|
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
|
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
|
)
|
|
|
|
// Server wraps the HTTP server and Gin router.
|
|
type Server struct {
|
|
httpServer *http.Server
|
|
router *gin.Engine
|
|
}
|
|
|
|
// NewServer creates a new HTTP server with all middleware and routes.
|
|
func NewServer(
|
|
cfg config.ConfigProvider,
|
|
log logger.Logger,
|
|
healthRegistry *health.Registry,
|
|
metricsRegistry *metrics.Metrics,
|
|
errorBus errorbus.ErrorPublisher,
|
|
) (*Server, error) {
|
|
// Set Gin mode
|
|
env := cfg.GetString("environment")
|
|
if env == "production" {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
|
|
router := gin.New()
|
|
|
|
// Add middleware (order matters!)
|
|
router.Use(RequestIDMiddleware())
|
|
router.Use(LoggingMiddleware(log))
|
|
router.Use(PanicRecoveryMiddleware(errorBus))
|
|
router.Use(metricsRegistry.HTTPMiddleware())
|
|
router.Use(CORSMiddleware())
|
|
|
|
// Request timeout middleware (optional, can be configured per route if needed)
|
|
// router.Use(TimeoutMiddleware(timeout))
|
|
|
|
// Register core routes
|
|
registerRoutes(router, healthRegistry, metricsRegistry)
|
|
|
|
// Get server configuration
|
|
port := cfg.GetInt("server.port")
|
|
if port == 0 {
|
|
port = 8080
|
|
}
|
|
host := cfg.GetString("server.host")
|
|
if host == "" {
|
|
host = "0.0.0.0"
|
|
}
|
|
|
|
readTimeout := cfg.GetDuration("server.read_timeout")
|
|
if readTimeout == 0 {
|
|
readTimeout = 30 * time.Second
|
|
}
|
|
|
|
writeTimeout := cfg.GetDuration("server.write_timeout")
|
|
if writeTimeout == 0 {
|
|
writeTimeout = 30 * time.Second
|
|
}
|
|
|
|
addr := fmt.Sprintf("%s:%d", host, port)
|
|
|
|
httpServer := &http.Server{
|
|
Addr: addr,
|
|
Handler: router,
|
|
ReadTimeout: readTimeout,
|
|
WriteTimeout: writeTimeout,
|
|
IdleTimeout: 120 * time.Second,
|
|
}
|
|
|
|
return &Server{
|
|
httpServer: httpServer,
|
|
router: router,
|
|
}, nil
|
|
}
|
|
|
|
// registerRoutes registers all core routes.
|
|
func registerRoutes(
|
|
router *gin.Engine,
|
|
healthRegistry *health.Registry,
|
|
metricsRegistry *metrics.Metrics,
|
|
) {
|
|
// Health endpoints
|
|
router.GET("/healthz", func(c *gin.Context) {
|
|
status := healthRegistry.LivenessCheck(c.Request.Context())
|
|
if status.Status == "healthy" {
|
|
c.JSON(http.StatusOK, status)
|
|
} else {
|
|
c.JSON(http.StatusServiceUnavailable, status)
|
|
}
|
|
})
|
|
|
|
router.GET("/ready", func(c *gin.Context) {
|
|
status := healthRegistry.ReadinessCheck(c.Request.Context())
|
|
if status.Status == "healthy" {
|
|
c.JSON(http.StatusOK, status)
|
|
} else {
|
|
c.JSON(http.StatusServiceUnavailable, status)
|
|
}
|
|
})
|
|
|
|
// Metrics endpoint
|
|
router.GET("/metrics", gin.WrapH(metricsRegistry.Handler()))
|
|
}
|
|
|
|
// Start starts the HTTP server.
|
|
func (s *Server) Start() error {
|
|
return s.httpServer.ListenAndServe()
|
|
}
|
|
|
|
// Shutdown gracefully shuts down the HTTP server.
|
|
func (s *Server) Shutdown(ctx context.Context) error {
|
|
return s.httpServer.Shutdown(ctx)
|
|
}
|
|
|
|
// Router returns the Gin router (for adding additional routes).
|
|
func (s *Server) Router() *gin.Engine {
|
|
return s.router
|
|
}
|
|
|