使用json keyfile从golang登录bigquery

Max*_*Max 6 go google-bigquery google-cloud-platform

所以我有一个如下所示的json密钥文件:

{
  "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----- ..."
  ...
}
Run Code Online (Sandbox Code Playgroud)

我想使用Golang将此文件登录到bigquery.我查看了https://github.com/GoogleCloudPlatform/google-cloud-go上的示例,但找不到任何与使用密钥文件创建新的bigquery客户端有关的内容.我错过了一些明显的东西吗

在python中,等价是:

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

        ...
Run Code Online (Sandbox Code Playgroud)

Max*_*Max 6

首先:我发布的文件是错误的密钥文件,有关更多详细信息,请使用oauth2client(Python)检查此答案:(“意外凭据类型”,“无”,“预期”,“ service_account”)

第二:这是对我有用的代码(列出可用的数据集):

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")
}
Run Code Online (Sandbox Code Playgroud)

今天花了永远的时间才发现……