新聞中心
基本介紹
請(qǐng)求流程往往會(huì)在上下文中共享一些自定義設(shè)置的變量,例如在請(qǐng)求開(kāi)始之前通過(guò)中間件設(shè)置一些變量,隨后在路由服務(wù)方法中可以獲取該變量并相應(yīng)對(duì)一些處理。這種需求非常常見(jiàn)。在?GOFrame?框架中,我們推薦使用?Context?上下文對(duì)象來(lái)處理流程共享的上下文變量,甚至將該對(duì)象進(jìn)一步傳遞到依賴(lài)的各個(gè)模塊方法中。該?Context?對(duì)象類(lèi)型實(shí)現(xiàn)了標(biāo)準(zhǔn)庫(kù)的?context.Context?接口,該接口往往會(huì)作為模塊間調(diào)用方法的第一個(gè)參數(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{})簡(jiǎn)要說(shuō)明:
- ?
GetCtx?方法用于獲取當(dāng)前的?context.Context?對(duì)象,作用同?Context?方法。 - ?
SetCtx?方法用于設(shè)置自定義的?context.Context?上下文對(duì)象。 - ?
GetCtxVar?方法用于獲取上下文變量,并可給定當(dāng)該變量不存在時(shí)的默認(rèn)值。 - ?
SetCtxVar?方法用于設(shè)置上下文變量。
使用示例
示例1,SetCtxVar/GetCtxVar
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()
}可以看到,我們可以通過(guò)?SetCtxVar?和?GetCtxVar?來(lái)設(shè)置和獲取自定義的變量,該變量生命周期僅限于當(dāng)前請(qǐng)求流程。
執(zhí)行后,訪問(wèn) http://127.0.0.1:8199/ ,頁(yè)面輸出內(nèi)容為:
HBm876TFCde435Tgf示例2,SetCtx
?SetCtx?方法常用于中間件中整合一些第三方的組件,例如第三方的鏈路跟蹤組件等等。
為簡(jiǎn)化示例,這里我們將上面的例子通過(guò)?SetCtx?方法來(lái)改造一下來(lái)做演示。
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í)行后,訪問(wèn) http://127.0.0.1:8199/ ,頁(yè)面輸出內(nèi)容為:
HBm876TFCde435Tgf 當(dāng)前標(biāo)題:創(chuàng)新互聯(lián)GoFrame教程:GoFrame請(qǐng)求輸入-Context
轉(zhuǎn)載來(lái)于:http://fisionsoft.com.cn/article/dpdogdp.html


咨詢(xún)
建站咨詢(xún)
