9

So I have a json keyfile that looks like this:

{
  "user_agent": null,
  "_scopes": "https://www.googleapis.com/auth/bigquery",
  "token_uri": "https://www.googleapis.com/oauth2/v4/token",
  "refresh_token": null,
  "_service_account_email": "...",
  "assertion_type": null,
  "_kwargs": {},
  "revoke_uri": "https://accounts.google.com/o/oauth2/revoke",
  "_private_key_pkcs8_pem": "-----BEGIN PRIVATE KEY----- ..."
  ...
}

I want to login using this file to bigquery, with Golang. I looked through the examples at https://github.com/GoogleCloudPlatform/google-cloud-go but couldn't find anything related there how to create a new bigquery client using the keyfile. Am I missing something obvious?

In python the quivalent is:

        credentials = ServiceAccountCredentials.from_json_keyfile_name(
                'keyfile.json',
                'https://www.googleapis.com/auth/bigquery')

        ...
Max
  • 15,693
  • 14
  • 81
  • 131

1 Answers1

9

First: the file I posted is the wrong keyfile, for more details, check this answer: ('Unexpected credentials type', None, 'Expected', 'service_account') with oauth2client (Python)

Second: this is the code that worked for me (listing the available datasets):

package main

import (
    "cloud.google.com/go/bigquery"
    "fmt"
    "golang.org/x/net/context"
    "google.golang.org/api/iterator"
    "google.golang.org/api/option"
)

func main() {
    ctx := context.Background()
    client, err := bigquery.NewClient(ctx, "project-name", option.WithCredentialsFile("keyfile.json"))

    if err != nil {
        panic(err.Error())
    }

    it := client.Datasets(ctx)
    for {
        dataset, err := it.Next()
        if err == iterator.Done {
            break
        }
        fmt.Println(dataset.DatasetID)
    }

    println("logged in")
}

That took forever to find out today …

Max
  • 15,693
  • 14
  • 81
  • 131
  • I think you should be able to export the path to this file in your env under `GOOGLE_APPLICATION_CREDENTIALS` which the lib should pick up when executing. Not sure though.. – Cristian Cavalli Sep 14 '17 at 16:51
  • Many official examples use `GOOGLE_APPLICATION_CREDENTIALS` but it's nice to have an explicit method as well. – Grokify Aug 24 '18 at 05:16