|
| 1 | +package roundtripware_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | + "github.com/stretchr/testify/require" |
| 11 | + "go.uber.org/zap/zaptest" |
| 12 | + |
| 13 | + keelhttp "github.com/foomo/keel/net/http" |
| 14 | + keelhttpcontext "github.com/foomo/keel/net/http/context" |
| 15 | + "github.com/foomo/keel/net/http/roundtripware" |
| 16 | +) |
| 17 | + |
| 18 | +func TestRequestID(t *testing.T) { |
| 19 | + l := zaptest.NewLogger(t) |
| 20 | + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 21 | + w.WriteHeader(http.StatusOK) |
| 22 | + })) |
| 23 | + defer svr.Close() |
| 24 | + |
| 25 | + client := keelhttp.NewHTTPClient( |
| 26 | + keelhttp.HTTPClientWithRoundTripware(l, |
| 27 | + roundtripware.RequestID(), |
| 28 | + ), |
| 29 | + ) |
| 30 | + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, svr.URL, nil) |
| 31 | + require.NoError(t, err) |
| 32 | + assert.Empty(t, req.Header.Get(keelhttp.HeaderXRequestID)) |
| 33 | + |
| 34 | + resp, err := client.Do(req) |
| 35 | + require.NoError(t, err) |
| 36 | + defer resp.Body.Close() |
| 37 | + assert.NotEmpty(t, req.Header.Get(keelhttp.HeaderXRequestID)) |
| 38 | +} |
| 39 | + |
| 40 | +func TestRequestID_Context(t *testing.T) { |
| 41 | + l := zaptest.NewLogger(t) |
| 42 | + svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 43 | + w.WriteHeader(http.StatusOK) |
| 44 | + })) |
| 45 | + defer svr.Close() |
| 46 | + |
| 47 | + client := keelhttp.NewHTTPClient( |
| 48 | + keelhttp.HTTPClientWithRoundTripware(l, |
| 49 | + roundtripware.RequestID(), |
| 50 | + ), |
| 51 | + ) |
| 52 | + ctx := keelhttpcontext.SetRequestID(context.Background(), "123456") |
| 53 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, svr.URL, nil) |
| 54 | + require.NoError(t, err) |
| 55 | + assert.Empty(t, req.Header.Get(keelhttp.HeaderXRequestID)) |
| 56 | + |
| 57 | + resp, err := client.Do(req) |
| 58 | + require.NoError(t, err) |
| 59 | + defer resp.Body.Close() |
| 60 | + assert.Equal(t, "123456", req.Header.Get(keelhttp.HeaderXRequestID)) |
| 61 | +} |
0 commit comments