github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_request_param_ctx.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package ghttp 8 9 import ( 10 "context" 11 "github.com/gogf/gf/container/gvar" 12 ) 13 14 // RequestFromCtx retrieves and returns the Request object from context. 15 func RequestFromCtx(ctx context.Context) *Request { 16 if v := ctx.Value(ctxKeyForRequest); v != nil { 17 return v.(*Request) 18 } 19 return nil 20 } 21 22 // Context is alias for function GetCtx. 23 // This function overwrites the http.Request.Context function. 24 // See GetCtx. 25 func (r *Request) Context() context.Context { 26 if r.context == nil { 27 r.context = r.Request.Context() 28 } 29 // Inject Request object into context. 30 if RequestFromCtx(r.context) == nil { 31 r.context = context.WithValue(r.context, ctxKeyForRequest, r) 32 } 33 return r.context 34 } 35 36 // GetCtx retrieves and returns the request's context. 37 func (r *Request) GetCtx() context.Context { 38 return r.Context() 39 } 40 41 // SetCtx custom context for current request. 42 func (r *Request) SetCtx(ctx context.Context) { 43 r.context = ctx 44 } 45 46 // GetCtxVar retrieves and returns a Var with given key name. 47 // The optional parameter <def> specifies the default value of the Var if given <key> 48 // does not exist in the context. 49 func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var { 50 value := r.Context().Value(key) 51 if value == nil && len(def) > 0 { 52 value = def[0] 53 } 54 return gvar.New(value) 55 } 56 57 // SetCtxVar sets custom parameter to context with key-value pair. 58 func (r *Request) SetCtxVar(key interface{}, value interface{}) { 59 r.context = context.WithValue(r.Context(), key, value) 60 }