github.com/godevsig/adaptiveservice@v0.9.23/context.go (about) 1 package adaptiveservice 2 3 import ( 4 "reflect" 5 ) 6 7 // Context represents a context. 8 type Context interface { 9 // PutVar puts value v to the underlying map overriding the old value of the same type. 10 PutVar(v interface{}) 11 12 // GetVar gets value that v points to from the underlying map, it panics if v 13 // is not a non-nil pointer. 14 // The value that v points to will be set to the value in the context if value 15 // of the same type has been putted to the map, 16 // otherwise zero value will be set. 17 GetVar(v interface{}) 18 19 // SetContext sets the context with value v which supposedly is a pointer to 20 // an instance of the struct associated to the connection. 21 // It panics if v is not a non-nil pointer. 22 // It is supposed to be called only once upon a new connection is connected. 23 SetContext(v interface{}) 24 // GetContext gets the context that has been set by SetContext. 25 GetContext() interface{} 26 } 27 28 type contextImpl struct { 29 kv map[reflect.Type]interface{} 30 ctx interface{} 31 } 32 33 func (c *contextImpl) PutVar(v interface{}) { 34 if c.kv == nil { 35 c.kv = make(map[reflect.Type]interface{}) 36 } 37 c.kv[reflect.TypeOf(v)] = v 38 } 39 40 func (c *contextImpl) GetVar(v interface{}) { 41 rptr := reflect.ValueOf(v) 42 if rptr.Kind() != reflect.Ptr || rptr.IsNil() { 43 panic("not a pointer or nil pointer") 44 } 45 rv := rptr.Elem() 46 tp := rv.Type() 47 if c.kv != nil { 48 if i, ok := c.kv[tp]; ok { 49 rv.Set(reflect.ValueOf(i)) 50 return 51 } 52 } 53 54 rv.Set(reflect.Zero(tp)) 55 } 56 57 func (c *contextImpl) SetContext(v interface{}) { 58 rptr := reflect.ValueOf(v) 59 if rptr.Kind() != reflect.Ptr || rptr.IsNil() { 60 panic("not a pointer or nil pointer") 61 } 62 c.ctx = v 63 } 64 65 func (c *contextImpl) GetContext() interface{} { 66 return c.ctx 67 }