Add traceId to the response headers (#919)
* Add traceId to the request headers * Add test cases * Update refactor code
This commit is contained in:
@@ -21,6 +21,8 @@ func TracingHandler(next http.Handler) http.Handler {
|
||||
defer span.Finish()
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
// Conveniently track error messages
|
||||
w.Header().Set(trace.TraceIdKey, span.TraceId())
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"github.com/tal-tech/go-zero/core/stringx"
|
||||
"github.com/tal-tech/go-zero/core/trace"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
@@ -11,14 +13,19 @@ import (
|
||||
|
||||
func TestTracingHandler(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
|
||||
req.Header.Set("X-Trace-ID", "theid")
|
||||
|
||||
traceId := stringx.RandId()
|
||||
req.Header.Set(trace.TraceIdKey, traceId)
|
||||
|
||||
handler := TracingHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
span, ok := r.Context().Value(tracespec.TracingKey).(tracespec.Trace)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "theid", span.TraceId())
|
||||
assert.Equal(t, traceId, span.TraceId())
|
||||
}))
|
||||
|
||||
resp := httptest.NewRecorder()
|
||||
handler.ServeHTTP(resp, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.Code)
|
||||
assert.Equal(t, traceId, resp.Header().Get(trace.TraceIdKey))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user