我是新来使用谷歌服务,我目前正试图阅读来自gmail API的电子邮件。但是,我陷入了访问令牌过期的场景中。
// get saved token from database / anywhere else
func getCachedToken() *oauth2.Token {
token := new(oauth2.Token)
token.AccessToken = "xxxxxxxx"
token.RefreshToken = "xxxxxx"
token.TokenType = "Bearer"
return token
}
func refreshToken(config *oauth2.Config, token *oauth2.Token) *http.Client {
return config.Client(context.Background(), token)
}
// Retrieve a token, saves the token, then returns the generated client.
func getClient(config *oauth2.Config) *http.Client {
tok := getTokenFromWeb(config)
fmt.Println(tok.RefreshToken)
fmt.Println(tok.AccessToken)
fmt.Println(tok.Expiry)
fmt.Println(tok.TokenType)
return config.Client(context.Background(), tok)
}
func main() (string, error) {
b, err := ioutil.ReadFile("credentials.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
// If modifying these scopes, delete your previously saved token.json.
config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope, gmail.GmailSendScope, gauth.UserinfoEmailScope, gauth.UserinfoProfileScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
token := getCachedToken()
accessToken := token.AccessToken
client := refreshToken(config, token)
if err != nil {
log.Fatalf("Unable to retrieve oauth client: %v", err)
}
if accessToken != token.AccessToken {
fmt.Println(token.RefreshToken)
fmt.Println(token.AccessToken)
fmt.Println(token.Expiry)
fmt.Println(token.TokenType)
} //THE TOKEN IS NOT CHANGED HERE WHEN THE ACCESS TOKEN EXPIRED
srv, err := gmail.New(client)
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
}
user := "me"
profile, err := srv.Users.GetProfile(user).Do()
if err != nil {
fmt.Println(err)
}
fmt.Println(profile.MessagesTotal)
return "test", nil
}