LoginSignup
10
2

More than 5 years have passed since last update.

GoでBigQueryへの認証をjson_keyfileで行う

Last updated at Posted at 2017-05-09

GoでBigQueryを利用するときにjson_keyfileを利用して認証をおこないたかったのですが、ドキュメントだけでの解決に時間がかかったので、そのまとめです。

環境

go 1.8

やり方

まずは、パッケージたちをインポートします。
ちなみに、"google.golang.org/api/iterator"BigQuery接続には関係ありませんが、データ取得時に利用しています。

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

そして、以下のようにすると、BigQueryのclientを取得することができます。

gcpKey := "json_keyfileのパス"
ctx := context.Background()
client, err := bigquery.NewClient(ctx, "プロジェクト名", option.WithServiceAccountFile(gcpKey))
if err != nil {
    panic(err.Error())
}
defer client.Close()

あとは、clientを利用して、クエリを投げるだけです。
以下はBigQurery上のsampleテーブルからデータを取得するコードです。

type Sample struct {
    ID         int    `bigquery:"id"`
    Comment    string `bigquery:"comment"`
}

sample := []Sample{}
q := client.Query(`SELECT * FROM [project:dataset.sample]`)
itt, err := q.Read(ctx)
if err != nil {
    return nil, err
}
for {
    var t Sample
    e := itt.Next(&t)
    if e == iterator.Done {
        break
    }
    if err != nil {
        return nil, err
    }
    sample = append(sample, t)
}

まとめ

GCPのAPIドキュメントはわかりにくくて大変ですね。
また、急に変更されることが多いので、記事が書かれた日付に注意しましょう。

参考

10
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
2