我正在尝试在令牌认证中间件中提取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的值在中间件中没有更新,因此,我在CreatedBy和UpdatedBy列中得到了“虚拟”值。我知道不鼓励使用全局变量,我对其他想法持开放态度。谢谢
发布于 2021-04-26 21:45:27
使用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。
https://stackoverflow.com/questions/67267065
复制相似问题