How to use OAuth 2.0 access token in Google Cloud for Go

Posted: , Modified:   Go Google Cloud Platform OAuth2


In OAuth 2.0 authorization for desktop applications using Google API, we’ve retrieved available zones by Google APIs Client Library for Go using a obtained access token.

Google Cloud for Go is another library to access Google Cloud Platform in Go. logadmin and logging packages I’ve introduced in Receive logs from Stackdriver Logging and Receive log entries from Stackdriver Logging by logging package are included in the Google Cloud for Go library.

In this post, I’ll introduce how to use an access token of OAuth 2.0 in that library.

Client of Google Cloud for Go

In Google APIs Client Library for Go APIs use http.Client to which an access token is attached. On the other hand, in Google Cloud for Go, constructors NewClient of clients receive a TokenSource as an option.

To create a TokenSource from an access token of oauth2.Token, we use a Config object. Since the config object is created with information required to authorization, the TokenSource created from the Config can renew the access token if it is expired.

For example, the following code creates a TokenSource and a client using the token source in order to retrieve log entries:

import (


const (
  authorizeEndpoint = ""
  tokenEndpoint = ""
  gcpScope = ""

func NewLoggingClient(ctx context.Context, token *oauth2.Token) (*logging.Client, error){

  cfg := &oauth2.Config{
    ClientID:     ClientID,
    ClientSecret: ClientSecret,
    Endpoint: oauth2.Endpoint{
      AuthURL:  authorizeEndpoint,
      TokenURL: tokenEndpoint,
    Scopes:      []string{gcpScope},

  return logging.NewClient(
    option.WithTokenSource(cfg.TokenSource(ctx, token)))