mirror of https://github.com/gin-gonic/gin.git
* 1.add GinContext; 2.more comment; 3.more test
This commit is contained in:
parent
1f66230395
commit
edb056830e
18
context.go
18
context.go
|
@ -82,15 +82,27 @@ type gin_context string
|
||||||
|
|
||||||
const gin_context_key gin_context = "gin_real_context"
|
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)
|
v := ctx.Value(gin_context_key)
|
||||||
if gc, ok := v.(*Context); ok {
|
if gc, ok := v.(*Context); ok {
|
||||||
return gc
|
return gc, nil
|
||||||
} else {
|
} 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 {
|
func NewContext(e *Engine) *Context {
|
||||||
c := &Context{engine: e}
|
c := &Context{engine: e}
|
||||||
c.Context = context.WithValue(context.Background(), gin_context_key, c) //With a value point to gin.Context
|
c.Context = context.WithValue(context.Background(), gin_context_key, c) //With a value point to gin.Context
|
||||||
|
|
|
@ -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) {
|
func UserFunc1Mock(ctx context.Context, t *testing.T) {
|
||||||
//add user defined value
|
//add user defined value
|
||||||
ctx = context.WithValue(ctx, "user_self_defined_value", "vvvvv")
|
ctx = context.WithValue(ctx, "user_self_defined_value", "vvvvv")
|
||||||
|
@ -1835,3 +1842,8 @@ func TestNewContextMustGin(t *testing.T) {
|
||||||
ctx := NewContext(nil)
|
ctx := NewContext(nil)
|
||||||
UserFunc1Mock(ctx, t) //use gin.Context as standard context
|
UserFunc1Mock(ctx, t) //use gin.Context as standard context
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestStandardContext(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
UserFunc3Mock(ctx, t)
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue