Home > Enterprise >  Beego - I need "context.Context" and not the Beego context
Beego - I need "context.Context" and not the Beego context

Time:03-09

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)

CodePudding user response:

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

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

  • Related