Restore various FromContext functions

Set the request context to the one generated for a chain to ensure
calls to FromContext and FromRequest for the various other x-libs
will result in using the same context object.
master
Kevin Conway 8 years ago
parent ed27b6fd65
commit 98eb90a4e5

@ -9,6 +9,8 @@ import (
"golang.org/x/net/context"
)
var testRequest, _ = http.NewRequest("GET", "/", nil)
func TestAppendHandlerC(t *testing.T) {
init := 0
h1 := func(next HandlerC) HandlerC {
@ -34,8 +36,8 @@ func TestAppendHandlerC(t *testing.T) {
assert.Equal(t, 2, ctx.Value("test"), "second handler should overwrite first handler's context value")
}))
h.ServeHTTP(nil, nil)
h.ServeHTTP(nil, nil)
h.ServeHTTP(nil, testRequest)
h.ServeHTTP(nil, testRequest)
assert.Equal(t, 1, init, "handler init called once")
}
@ -70,8 +72,8 @@ func TestAppendHandler(t *testing.T) {
assert.NotNil(t, r)
}))
h.ServeHTTP(nil, nil)
h.ServeHTTP(nil, nil)
h.ServeHTTP(nil, testRequest)
h.ServeHTTP(nil, testRequest)
// There's no safe way to not initialize non ctx aware handlers on each request :/
//assert.Equal(t, 1, init, "handler init called once")
}
@ -106,7 +108,7 @@ func TestChainHandlerC(t *testing.T) {
}))
mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
h.ServeHTTPC(mainCtx, nil, nil)
h.ServeHTTPC(mainCtx, nil, testRequest)
assert.Equal(t, 3, handlerCalls, "all handler called once")
}
@ -149,7 +151,7 @@ func TestAdd(t *testing.T) {
}))
mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
h.ServeHTTPC(mainCtx, nil, nil)
h.ServeHTTPC(mainCtx, nil, testRequest)
assert.Equal(t, 4, handlerCalls, "all handler called once")
}
@ -201,9 +203,9 @@ func TestWith(t *testing.T) {
}))
mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
h.ServeHTTPC(mainCtx, nil, nil)
h.ServeHTTPC(mainCtx, nil, testRequest)
assert.Equal(t, 2, handlerCalls, "all handlers called once")
handlerCalls = 0
i.ServeHTTPC(mainCtx, nil, nil)
i.ServeHTTPC(mainCtx, nil, testRequest)
assert.Equal(t, 4, handlerCalls, "all handler called once")
}

@ -37,6 +37,6 @@ func (f HandlerFuncC) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *
// http.Handler and context aware handlers.
func New(ctx context.Context, h HandlerC) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTPC(ctx, w, r)
h.ServeHTTPC(ctx, w, r.WithContext(ctx))
})
}

@ -56,6 +56,10 @@ func TestHandlerFunc(t *testing.T) {
xh := HandlerFuncC(func(context.Context, http.ResponseWriter, *http.Request) {
ok = true
})
xh.ServeHTTPC(nil, nil, nil)
r, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
log.Fatal(err)
}
xh.ServeHTTPC(context.Background(), nil, r)
assert.True(t, ok)
}

Loading…
Cancel
Save