上下文变量指的是标准库的context.Context,是一个接口对象。主要用于goroutine的异步IO控制,以及流程变量传递。

在Go的HTTP请求流程中,不存在”全局变量”获取请求参数的方式,只有将上下文context变量传递到后续流程的方法中,而context上下文变量即包含了所有需要传递的共享变量。并且该context中的共享变量应当是事先约定的,并且往往存储为对象指针形式。

结构定义

在该示例中,我们的上下文变量的数据结构定义为:https://github.com/gogf/gf-demos/blob/master/app/model/context.go

  1. // 请求上下文结构
  2. type Context struct {
  3. Session *ghttp.Session // 当前Session管理对象
  4. User *ContextUser // 上下文用户信息
  5. }
  6. // 请求上下文中的用户信息
  7. type ContextUser struct {
  8. Id uint // 用户ID
  9. Passport string // 用户账号
  10. Nickname string // 用户名称
  11. }

逻辑封装

由于该上下文对象也是和业务逻辑相关的,因此我们需要通过service对象将上下文变量封装起来再供其他模块使用。https://github.com/gogf/gf-demos/blob/master/app/service/context.go
image2020-12-25_11-3-19.png

上下文变量注入

上下文的变量必须在请求一开始便注入到请求流程中,以便于其他方法调用,因此我们使用中间件来实现。
https://github.com/gogf/gf-demos/blob/168e049e58528413cd248c05c729840e552ece94/app/service/middleware.go#L15
image2020-12-24_17-16-43.png

上下文变量使用

约定俗成的,方法的第一个参数往往预留给context.Context类型参数使用,以便接受上下文变量,特别是service层的方法。例如:https://github.com/gogf/gf-demos/blob/master/app/service/user.go
image2020-12-24_17-19-40.png