新聞中心
這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)GoFrame教程:GoFrame請求輸入-Context
基本介紹
請求流程往往會在上下文中共享一些自定義設置的變量,例如在請求開始之前通過中間件設置一些變量,隨后在路由服務方法中可以獲取該變量并相應對一些處理。這種需求非常常見。在?GOFrame?框架中,我們推薦使用?Context?上下文對象來處理流程共享的上下文變量,甚至將該對象進一步傳遞到依賴的各個模塊方法中。該?Context?對象類型實現(xiàn)了標準庫的?context.Context?接口,該接口往往會作為模塊間調用方法的第一個參數(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?方法用于獲取當前的?context.Context?對象,作用同?Context?方法。 - ?
SetCtx?方法用于設置自定義的?context.Context?上下文對象。 - ?
GetCtxVar?方法用于獲取上下文變量,并可給定當該變量不存在時的默認值。 - ?
SetCtxVar?方法用于設置上下文變量。
使用示例
示例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()
}可以看到,我們可以通過?SetCtxVar?和?GetCtxVar?來設置和獲取自定義的變量,該變量生命周期僅限于當前請求流程。
執(zhí)行后,訪問 http://127.0.0.1:8199/ ,頁面輸出內容為:
HBm876TFCde435Tgf示例2,SetCtx
?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/ ,頁面輸出內容為:
HBm876TFCde435Tgf 標題名稱:創(chuàng)新互聯(lián)GoFrame教程:GoFrame請求輸入-Context
網址分享:http://www.5511xx.com/article/dpdogdp.html


咨詢
建站咨詢
