2017-09-14 122 views
1

從golang BIGQUERY所以我有一個JSON密鑰文件,看起來像這樣:登錄到使用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----- ..." 
    ... 
} 

我想用這個文件的BigQuery,與Golang登錄。我查看了https://github.com/GoogleCloudPlatform/google-cloud-go的示例,但是找不到與如何使用密鑰文件創建新的bigquery客戶端相關的任何內容。我錯過了明顯的東西嗎?

在Python中quivalent是:

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

     ... 

回答

0

第一:我張貼的文件是錯誤的密鑰文件,瞭解更多詳情,請查看這個答案:('Unexpected credentials type', None, 'Expected', 'service_account') with oauth2client (Python)

二:這是對工作的代碼我(列出了可用的數據集):

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") 
} 

那沒完沒了的今天,找出...

+0

我認爲你應該能夠在你的env下的'GOOGLE_APPLICATION_CREDENTIALS'下導出這個文件的路徑,這個文件在執行的時候應該會被lib讀取。雖然不確定.. –