W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
請求流程往往會在上下文中共享一些自定義設(shè)置的變量,例如在請求開始之前通過中間件設(shè)置一些變量,隨后在路由服務(wù)方法中可以獲取該變量并相應(yīng)對一些處理。這種需求非常常見。在?GoFrame
?框架中,我們推薦使用?Context
?上下文對象來處理流程共享的上下文變量,甚至將該對象進(jìn)一步傳遞到依賴的各個模塊方法中。該?Context
?對象類型實(shí)現(xiàn)了標(biāo)準(zhǔn)庫的?context.Context
?接口,該接口往往會作為模塊間調(diào)用方法的第一個參數(shù),該接口參數(shù)也是Golang官方推薦的在模塊間傳遞上下文變量的推薦方式。
方法列表:
func (r *Request) GetCtx() context.Context
func (r *Request) SetCtx(ctx context.Context)
func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var
func (r *Request) SetCtxVar(key interface{}, value interface{})
簡要說明:
GetCtx
?方法用于獲取當(dāng)前的?context.Context
?對象,作用同?Context
?方法。
SetCtx
?方法用于設(shè)置自定義的?context.Context
?上下文對象。
GetCtxVar
?方法用于獲取上下文變量,并可給定當(dāng)該變量不存在時(shí)的默認(rèn)值。
SetCtxVar
?方法用于設(shè)置上下文變量。package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
const (
TraceIdName = "trace-id"
)
func main() {
s := g.Server()
s.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(func(r *ghttp.Request) {
r.SetCtxVar(TraceIdName, "HBm876TFCde435Tgf")
r.Middleware.Next()
})
group.ALL("/", func(r *ghttp.Request) {
r.Response.Write(r.GetCtxVar(TraceIdName))
})
})
s.SetPort(8199)
s.Run()
}
可以看到,我們可以通過?SetCtxVar
?和?GetCtxVar
?來設(shè)置和獲取自定義的變量,該變量生命周期僅限于當(dāng)前請求流程。
執(zhí)行后,訪問 http://127.0.0.1:8199/ ,頁面輸出內(nèi)容為:
HBm876TFCde435Tgf
?SetCtx
?方法常用于中間件中整合一些第三方的組件,例如第三方的鏈路跟蹤組件等等。
為簡化示例,這里我們將上面的例子通過?SetCtx
?方法來改造一下來做演示。
package main
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
const (
TraceIdName = "trace-id"
)
func main() {
s := g.Server()
s.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(func(r *ghttp.Request) {
ctx := context.WithValue(r.Context(), TraceIdName, "HBm876TFCde435Tgf")
r.SetCtx(ctx)
r.Middleware.Next()
})
group.ALL("/", func(r *ghttp.Request) {
r.Response.Write(r.Context().Value(TraceIdName))
// 也可以使用
// r.Response.Write(r.GetCtxVar(TraceIdName))
})
})
s.SetPort(8199)
s.Run()
}
執(zhí)行后,訪問 http://127.0.0.1:8199/ ,頁面輸出內(nèi)容為:
HBm876TFCde435Tgf
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: