Add OpenTelemetry instrumentation with middleware-only approach

This commit is contained in:
Mistral Vibe
2026-04-04 12:19:48 +02:00
committed by Gabriel Radureau
parent c38d7c6d76
commit 36f0b79b90
13 changed files with 452 additions and 46 deletions

View File

@@ -6,6 +6,7 @@ import (
"DanceLessonsCoach/pkg/config"
"DanceLessonsCoach/pkg/greet"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
@@ -13,14 +14,16 @@ import (
)
type Server struct {
router *chi.Mux
readyCtx context.Context
router *chi.Mux
readyCtx context.Context
withOTEL bool
}
func NewServer(cfg *config.Config, readyCtx context.Context) *Server {
s := &Server{
router: chi.NewRouter(),
readyCtx: readyCtx,
router: chi.NewRouter(),
readyCtx: readyCtx,
withOTEL: cfg.GetTelemetryEnabled(),
}
s.setupRoutes()
return s
@@ -41,7 +44,7 @@ func (s *Server) setupRoutes() {
// API routes
s.router.Route("/api/v1", func(r chi.Router) {
r.Use(s.apiMiddlewares()...)
r.Use(s.getAllMiddlewares()...)
s.registerApiV1Routes(r)
})
}
@@ -54,11 +57,20 @@ func (s *Server) registerApiV1Routes(r chi.Router) {
})
}
func (s *Server) apiMiddlewares() []func(http.Handler) http.Handler {
return []func(http.Handler) http.Handler{
// getAllMiddlewares returns all middleware including OpenTelemetry if enabled
func (s *Server) getAllMiddlewares() []func(http.Handler) http.Handler {
middlewares := []func(http.Handler) http.Handler{
middleware.StripSlashes,
middleware.Recoverer,
}
if s.withOTEL {
middlewares = append(middlewares, func(next http.Handler) http.Handler {
return otelhttp.NewHandler(next, "")
})
}
return middlewares
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
@@ -68,7 +80,7 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
func (s *Server) handleReadiness(w http.ResponseWriter, r *http.Request) {
log.Info().Msg("Readiness check requested")
select {
case <-s.readyCtx.Done():
log.Info().Msg("Readiness check: not ready (shutting down)")