52 lines
1.7 KiB
Go
52 lines
1.7 KiB
Go
package tracing
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
)
|
|
|
|
// HTTPClientWithTracing est un wrapper autour de http.Client qui propage automatiquement le contexte de tracing
|
|
type HTTPClientWithTracing struct {
|
|
client *http.Client
|
|
}
|
|
|
|
// NewHTTPClientWithTracing crée un nouveau client HTTP avec propagation automatique du tracing
|
|
func NewHTTPClientWithTracing(client *http.Client) *HTTPClientWithTracing {
|
|
if client == nil {
|
|
client = &http.Client{}
|
|
}
|
|
return &HTTPClientWithTracing{
|
|
client: client,
|
|
}
|
|
}
|
|
|
|
// Do exécute une requête HTTP en propageant automatiquement le contexte de tracing
|
|
func (c *HTTPClientWithTracing) Do(req *http.Request) (*http.Response, error) {
|
|
// Extraire le contexte de tracing depuis le contexte de la requête
|
|
if traceCtx := FromContext(req.Context()); traceCtx != nil {
|
|
// Injecter le contexte de tracing dans les headers
|
|
InjectTraceContext(req, traceCtx)
|
|
}
|
|
return c.client.Do(req)
|
|
}
|
|
|
|
// DoWithContext exécute une requête HTTP avec un contexte et propage le tracing
|
|
func (c *HTTPClientWithTracing) DoWithContext(ctx context.Context, req *http.Request) (*http.Response, error) {
|
|
// Utiliser le contexte fourni
|
|
req = req.WithContext(ctx)
|
|
|
|
// Extraire le contexte de tracing depuis le contexte
|
|
if traceCtx := FromContext(ctx); traceCtx != nil {
|
|
// Injecter le contexte de tracing dans les headers
|
|
InjectTraceContext(req, traceCtx)
|
|
}
|
|
return c.client.Do(req)
|
|
}
|
|
|
|
// InjectTraceContextInRequest injecte le contexte de tracing dans une requête HTTP existante
|
|
// Helper function pour les cas où on ne peut pas utiliser HTTPClientWithTracing
|
|
func InjectTraceContextInRequest(req *http.Request) {
|
|
if traceCtx := FromContext(req.Context()); traceCtx != nil {
|
|
InjectTraceContext(req, traceCtx)
|
|
}
|
|
}
|