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) +}