github.com/gogf/gf/v2@v2.7.4/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 12 "github.com/gogf/gf/v2/container/gvar" 13 "github.com/gogf/gf/v2/os/gctx" 14 ) 15 16 // RequestFromCtx retrieves and returns the Request object from context. 17 func RequestFromCtx(ctx context.Context) *Request { 18 if v := ctx.Value(ctxKeyForRequest); v != nil { 19 return v.(*Request) 20 } 21 return nil 22 } 23 24 // Context is alias for function GetCtx. 25 // This function overwrites the http.Request.Context function. 26 // See GetCtx. 27 func (r *Request) Context() context.Context { 28 var ctx = r.Request.Context() 29 // Check and inject Request object into context. 30 if RequestFromCtx(ctx) == nil { 31 // Inject Request object into context. 32 ctx = context.WithValue(ctx, ctxKeyForRequest, r) 33 // Add default tracing info if using default tracing provider. 34 ctx = gctx.WithCtx(ctx) 35 // Update the values of the original HTTP request. 36 *r.Request = *r.Request.WithContext(ctx) 37 } 38 return ctx 39 } 40 41 // GetCtx retrieves and returns the request's context. 42 // Its alias of function Context,to be relevant with function SetCtx. 43 func (r *Request) GetCtx() context.Context { 44 return r.Context() 45 } 46 47 // GetNeverDoneCtx creates and returns a never done context object, 48 // which forbids the context manually done, to make the context can be propagated to asynchronous goroutines, 49 // which will not be affected by the HTTP request ends. 50 // 51 // This change is considered for common usage habits of developers for context propagation 52 // in multiple goroutines creation in one HTTP request. 53 func (r *Request) GetNeverDoneCtx() context.Context { 54 return gctx.NeverDone(r.Context()) 55 } 56 57 // SetCtx custom context for current request. 58 func (r *Request) SetCtx(ctx context.Context) { 59 *r.Request = *r.WithContext(ctx) 60 } 61 62 // GetCtxVar retrieves and returns a Var with a given key name. 63 // The optional parameter `def` specifies the default value of the Var if given `key` 64 // does not exist in the context. 65 func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var { 66 value := r.Context().Value(key) 67 if value == nil && len(def) > 0 { 68 value = def[0] 69 } 70 return gvar.New(value) 71 } 72 73 // SetCtxVar sets custom parameter to context with key-value pairs. 74 func (r *Request) SetCtxVar(key interface{}, value interface{}) { 75 var ctx = r.Context() 76 ctx = context.WithValue(ctx, key, value) 77 *r.Request = *r.Request.WithContext(ctx) 78 }