Getting values from parent context

This commit is contained in:
Stefan Scheidewig 2022-06-18 09:16:57 +02:00
parent 819562d5d8
commit ab78498b23
2 changed files with 57 additions and 7 deletions

View File

@ -12,6 +12,7 @@ import (
type httpContext struct { type httpContext struct {
context.Context context.Context
parentCtx context.Context
res http.ResponseWriter res http.ResponseWriter
req *http.Request req *http.Request
body *bodyReader body *bodyReader
@ -19,9 +20,17 @@ type httpContext struct {
func newContext(w http.ResponseWriter, r *http.Request) *httpContext { func newContext(w http.ResponseWriter, r *http.Request) *httpContext {
return &httpContext{ return &httpContext{
Context: r.Context(), Context: context.Background(),
parentCtx: r.Context(),
res: w, res: w,
req: r, req: r,
body: nil, // body can be filled later for PATCH requests body: nil, // body can be filled later for PATCH requests
} }
} }
func (hctx *httpContext) Value(key interface{}) interface{} {
if v := hctx.Context.Value(key); v != nil {
return v
}
return hctx.parentCtx.Value(key)
}

View File

@ -0,0 +1,41 @@
package handler
import (
"context"
"errors"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"testing"
)
func TestContext(t *testing.T) {
t.Run("new context returns values from parent context", func(t *testing.T) {
parentCtx := context.WithValue(context.Background(), "test", "value")
req := http.Request{}
reqWithCtx := req.WithContext(parentCtx)
ctx := newContext(&httptest.ResponseRecorder{}, reqWithCtx)
ctxToTest := context.WithValue(ctx, "another", "testvalue")
a := assert.New(t)
a.Equal("testvalue", ctxToTest.Value("another"))
a.Equal("value", ctxToTest.Value("test"))
})
t.Run("parent context cancellation does not cancel the httpContext", func(t *testing.T) {
parentCtx := context.Background()
req := http.Request{}
reqWithCtx := req.WithContext(parentCtx)
ctx := newContext(&httptest.ResponseRecorder{}, reqWithCtx)
parentCtx.Done()
a := assert.New(t)
a.False(errors.Is(ctx.Err(), context.Canceled))
})
}