From edb056830e41cb2eb3c1a6a22df68af81818db93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?unlikezhang=28=E5=BC=A0=E6=89=AC=29?= Date: Sun, 28 Apr 2019 22:37:54 +0000 Subject: [PATCH] * 1.add GinContext; 2.more comment; 3.more test --- context.go | 18 +++++++++++++++--- context_test.go | 12 ++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/context.go b/context.go index 065cd122..10a233db 100644 --- a/context.go +++ b/context.go @@ -82,15 +82,27 @@ type gin_context string const gin_context_key gin_context = "gin_real_context" -func MustGinContext(ctx context.Context) *Context { +// GinContext try to Get gin.Context from context.Context +func GinContext(ctx context.Context) (*Context, error) { v := ctx.Value(gin_context_key) if gc, ok := v.(*Context); ok { - return gc + return gc, nil } else { - panic(fmt.Sprintf("MustGinContext fail,TypeOf(v):%s", reflect.TypeOf(v))) + return nil, fmt.Errorf("GinContext fail,TypeOf(v):%s", reflect.TypeOf(v)) } } +// MustGinContext try to gin.Context from context.Context +// Will panic if fail +func MustGinContext(ctx context.Context) *Context { + if gc, err := GinContext(ctx); err == nil { + return gc + } else { + panic(fmt.Sprintf("MustGinContext fail:%s", err)) + } +} + +// NewContext wrap gin.Context with context.Context func NewContext(e *Engine) *Context { c := &Context{engine: e} c.Context = context.WithValue(context.Background(), gin_context_key, c) //With a value point to gin.Context diff --git a/context_test.go b/context_test.go index 909fd1e0..1feb0ae4 100644 --- a/context_test.go +++ b/context_test.go @@ -1823,6 +1823,13 @@ func UserFunc2Mock(ctx context.Context, t *testing.T) { }) } +func UserFunc3Mock(ctx context.Context, t *testing.T) { + assert.Panics(t, func() { + gc := MustGinContext(ctx) //get gin.Context back as need + assert.Equal(t, gc, nil) + }) +} + func UserFunc1Mock(ctx context.Context, t *testing.T) { //add user defined value ctx = context.WithValue(ctx, "user_self_defined_value", "vvvvv") @@ -1835,3 +1842,8 @@ func TestNewContextMustGin(t *testing.T) { ctx := NewContext(nil) UserFunc1Mock(ctx, t) //use gin.Context as standard context } + +func TestStandardContext(t *testing.T) { + ctx := context.Background() + UserFunc3Mock(ctx, t) +}