我正在try 编写一个函数来验证Google id令牌.
oauth2 package要求我在创建新服务时通过上下文,如下所示:
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()
在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)
// Type mismatch
services.ValidateToken(c.Ctx, requestParams.Google_id_token)
我怎样才能到达需要传递给OAuth2库的上下文?
编辑:我正在通过传递上下文来解决这个问题.Background(),但我不确定自己是否完全理解这种方法的副作用.我对Golang很陌生,感觉背景背景应该只在"更高"的层次上使用?
func ValidateToken(idToken string) {
ctx := context.Background()
oauth2Service, err := oauth2.NewService(ctx)