go - 如何将上下文值从 Gin 中间件传播到 gqlgen 解析器?

标签 go graphql go-gin gqlgen go-context

我正在尝试提取 token 身份验证中间件中的 user_id 并将其传递给 gqlgen的 graphql 解析器函数(用于填充 GraphQL 模式的 created_by 和 updated_by 列)。身份验证部分工作没有任何问题。

Gin 中间件:

    var UID = "dummy"
    func TokenAuthMiddleware() gin.HandlerFunc {
        return func(c *gin.Context) {
            err := auth.TokenValid(c.Request)
            if err != nil {
                c.JSON(http.StatusUnauthorized, "You need to be authorized to access this route")
                c.Abort()
                return
            }
            //
            UID, _ = auth.ExtractTokenID(c.Request)
            //c.Set("user_id", UID)
            
            c.Next()
        }
    }

    func GetUID() string {
        return UID
    }

graphql 解析器:

    var ConstID = middleware.GetUID()
    
    func (r *mutationResolver) CreateFarmer(ctx context.Context, input model.NewFarmer) (*model.Farmer, error) {
        //Fetch Connection and close db
        db := model.FetchConnection()
        defer db.Close()
    
        //var ConstID, _ = uuid.NewRandom()
    
        log.Println(ctx)
    
        farmer := model.Farmer{Name: input.Name, Surname: input.Surname, Dob: input.Dob, Fin: input.Fin, PlotLocLat: input.PlotLocLat, PlotLocLong: input.PlotLocLong, CreatedAt: time.Now(), UpdatedAt: time.Now(), CreatedBy: ConstID, UpdatedBy: ConstID}
        db.Create(&farmer)
        return &farmer, nil
    }

在这里,我尝试使用全局变量 UID 来做到这一点,但是 UID 的值没有在中间件中更新,因此,我在 CreatedByUpdatedBy 列。我知道不鼓励使用全局变量,我对其他想法持开放态度。谢谢

最佳答案

使用 context.Context 传播值。

如果您使用 gqlgen ,您必须记住传递给解析器函数的 context.Context 实例来自 *http.Request(假设您按照 gqlgen 文档中的建议设置了集成) .

因此,对于 Go-Gin,您应该能够通过一些额外的管道来做到这一点:

func TokenAuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        UID := // ... get the UID somehow
        
        ctx := context.WithValue(c.Request.Context(), "user_id", UID)
        c.Request = c.Request.WithContext(ctx)
        c.Next()
    }
}

然后您通常会在解析器中获取值:

func (r *mutationResolver) CreateFarmer(ctx context.Context, input model.NewFarmer) (*model.Farmer, error) {
    UID, _ := ctx.Value("user_id").(string)
    // ...
}

还有一个示例(虽然没有 Gin)here

关于go - 如何将上下文值从 Gin 中间件传播到 gqlgen 解析器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67267065/

相关文章:

google-app-engine - "datastore: internal error: server returned the wrong number of entities"检索不存在的对象时

go - 在golang中使用gin包为特定路由表达中间件?

reactjs - 如何通过react/axios和golang/gin上传图片到S3

Golang如何模板化嵌套结构?

algorithm - 如何用golang得到小数点后两位的长度?

git - 如何通过 SSH 在 CI 构建成功上部署我的 webapp?

flutter - 如何使用 graphQL 将 api 的响应转换为 flutter 中的普通旧 Dart 对象?

wordpress - 自定义字段未保存

elasticsearch - 使用 NestJS/Elastic 对服务进行单元测试的正确方法是什么

go - 如何缩短 Golang 中具有相同类型属性的结构声明?