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,16 +12,25 @@ import (
type httpContext struct { type httpContext struct {
context.Context context.Context
res http.ResponseWriter parentCtx context.Context
req *http.Request res http.ResponseWriter
body *bodyReader req *http.Request
body *bodyReader
} }
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(),
res: w, parentCtx: r.Context(),
req: r, res: w,
body: nil, // body can be filled later for PATCH requests req: r,
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))
})
}