Beego – 我需要 “context.Context” 而不是 Beego 的上下文

huangapple go评论91阅读模式
英文:

Beego - I need "context.Context" and not the Beego context

问题

我正在尝试编写一个函数来验证 Google id token。

oauth2 package 要求我在创建新服务时传入上下文,像这样:

package services

import (
	"context"
	"google.golang.org/api/oauth2/v2"
)

func ValidateToken(ctx *context.Context, idToken string) {
    // 我需要将 context.Context 传递给 oauth2 库
	oauth2Service, err := oauth2.NewService(*ctx)
	tokenInfoCall := oauth2Service.Tokeninfo()
	tokenInfoCall.IdToken(idToken)
	tokenInfo, err := tokenInfoCall.Do()

在 Beego 中,this.Ctx 是 Beego 上下文模块的一个实例,所以这段代码无法编译通过:

func (c *TokenController) Post(ctx *context.Context) {
    requestParams := struct {
        Google_id_token string
    }{}
    err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestParams)
    // 类型不匹配
    services.ValidateToken(c.Ctx, requestParams.Google_id_token)

我该如何获取需要传递给 OAuth2 库的上下文?

编辑:我通过传递 context.Background() 来解决这个问题,但我不确定这样做是否完全理解了其副作用。我对 Golang 还比较新手,感觉后台上下文应该只在“更高级别”上使用?

func ValidateToken(idToken string) {
    ctx := context.Background()
    oauth2Service, err := oauth2.NewService(ctx)
英文:

I am trying to write a function that will validate a Google id token.

The oauth2 package requires me to pass in the context when creating a new service, like this:

package services

import (
	"context"
	"google.golang.org/api/oauth2/v2"
)

func ValidateToken(ctx *context.Context, idToken string) {
    // I need to pass context.Context in to the oauth2 library
	oauth2Service, err := oauth2.NewService(*ctx)
	tokenInfoCall := oauth2Service.Tokeninfo()
	tokenInfoCall.IdToken(idToken)
	tokenInfo, err := tokenInfoCall.Do()

In Beego this.Ctx is an instance of the Beego context module, so this code won't compile:

func (c *TokenController) Post(ctx *context.Context) {
    requestParams := struct {
	    Google_id_token string
    }{}
    err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestParams)
    // Type mismatch
    services.ValidateToken(c.Ctx, requestParams.Google_id_token)

How can I reach the context that I need to pass in to the OAuth2 library?

Edit: I'm working around it by passing in context.Background(), but I'm not sure that I fully understand the side effects of this. I'm pretty new to Golang and it feels like background context should only be used at "higher" levels?

func ValidateToken(idToken string) {
	ctx := context.Background()
	oauth2Service, err := oauth2.NewService(ctx)

答案1

得分: 1

请尝试这样写:c.Ctx.Request.Context()

另外,在函数ValidateToken的参数ctx中不要使用指针,因为stdlib中的context.Context是一个接口。

英文:

try this : c.Ctx.Request.Context()

also don't use pointer in arg ctx in function ValidateToken because context.Context in stdlib is interface

huangapple
  • 本文由 发表于 2022年3月8日 18:31:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/71393488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定