Skip to content

Latest commit

 

History

History
65 lines (42 loc) · 1.83 KB

context.md

File metadata and controls

65 lines (42 loc) · 1.83 KB

上下文变量

请求流程往往会在上下文中共享一些自定义设置的变量,例如在请求开始之前通过中间件设置一些变量,随后在路由服务方法中可以获取该变量并相应对一些处理。这种需求非常常见。在GF框架中,我们推荐使用Context上下文对象来处理流程共享的上下文变量,甚至将该对象进一步传递到依赖的各个模块方法中。该Context对象类型实现了标准库的context.Context接口,该接口往往会作为模块间调用方法的第一个参数,该接口参数也是Golang官方推荐的在模块间传递上下文变量的推荐方式。

方法列表:

func (r *Request) GetCtx() context.Context
func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var
func (r *Request) SetCtxVar(key interface{}, value interface{})

简要说明:

  1. GetCtx方法用于获取当前的context.Context对象,作用同Context方法。
  2. GetCtxVar方法用于获取上下文变量,并可给定当该变量不存在时的默认值。
  3. SetCtxVar方法用于设置上下文变量。

使用示例:

package main

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/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()
}

可以看到,我们可以通过SetCtxVarGetCtxVar来设置和获取自定义的变量,该变量生命周期仅限于当前请求流程。

执行后,访问 http://127.0.0.1:8199/ ,页面输出内容为:

HBm876TFCde435Tgf