|
| 1 | +package middleware |
| 2 | + |
| 3 | +import ( |
| 4 | + stdcontext "context" |
| 5 | + stderrors "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "net/http/httptest" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/go-openapi/runtime/internal/testing/petstore" |
| 13 | + "github.com/go-openapi/testify/v2/assert" |
| 14 | + "github.com/go-openapi/testify/v2/require" |
| 15 | +) |
| 16 | + |
| 17 | +func TestRouterContext_Issue375(t *testing.T) { |
| 18 | + spec, api := petstore.NewAPI(t) |
| 19 | + spec.Spec().BasePath = "/api/" |
| 20 | + context := NewContext(spec, api, nil) |
| 21 | + |
| 22 | + type authCtxKey uint8 |
| 23 | + const authCtx authCtxKey = iota + 1 |
| 24 | + authCtxErr := stderrors.New("test error in context") |
| 25 | + |
| 26 | + mw := NewRouter(context, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 27 | + // check context after API middleware |
| 28 | + authContext := stdcontext.WithValue(r.Context(), authCtx, authCtxErr) |
| 29 | + *r = *r.WithContext(authContext) |
| 30 | + })) |
| 31 | + |
| 32 | + start := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 33 | + t.Logf("calling API router with context: %v", authCtxErr) |
| 34 | + mw.ServeHTTP(w, r) |
| 35 | + |
| 36 | + value := r.Context().Value(authCtx) |
| 37 | + assert.NotNilf(t, value, "end of middleware chain: expected to find authCtx in request context") |
| 38 | + |
| 39 | + if value == nil { |
| 40 | + w.WriteHeader(http.StatusInternalServerError) |
| 41 | + } |
| 42 | + |
| 43 | + errAuth, ok := value.(error) |
| 44 | + assert.Truef(t, ok, "expected authCtx to be an error, but got: %T", value) |
| 45 | + t.Logf("got context from request: %v", errAuth) |
| 46 | + fmt.Fprintf(w, "%v", errAuth) |
| 47 | + w.WriteHeader(http.StatusOK) |
| 48 | + |
| 49 | + // *r = *r.WithContext(authContext) |
| 50 | + // mw.ServeHTTP(w, r) |
| 51 | + }) |
| 52 | + |
| 53 | + recorder := httptest.NewRecorder() |
| 54 | + request, err := http.NewRequestWithContext(stdcontext.Background(), http.MethodGet, "/api/pets/123", nil) |
| 55 | + require.NoError(t, err) |
| 56 | + |
| 57 | + start.ServeHTTP(recorder, request) |
| 58 | + assert.Equal(t, http.StatusOK, recorder.Code) |
| 59 | + |
| 60 | + res := recorder.Result() |
| 61 | + require.NotNil(t, res.Body) |
| 62 | + msg, err := io.ReadAll(res.Body) |
| 63 | + require.NoError(t, err) |
| 64 | + t.Logf("response message: %q", string(msg)) |
| 65 | +} |
0 commit comments