Add OpenTelemetry instrumentation with middleware-only approach
This commit is contained in:
@@ -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)")
|
||||
|
||||
Reference in New Issue
Block a user