5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoでFirebase CloudFirestore接続、値取得まで

Last updated at Posted at 2019-04-12

Firebase共通鍵の入手

Firebaseコンソールへログイン
「設定」→「プロジェクトの設定」で設定画面を表示
「サービスアカウント」タブを押し、Firebase Admin SDKを表示する

Admin SDK 構成スニペットでGoを選択
【新しい秘密鍵の生成】ボタンから秘密鍵(json)をダウンロード

クライント接続

package main

import (
	"fmt"

	"golang.org/x/net/context"

	firebase "firebase.google.com/go"
	"google.golang.org/api/option"
)

func main() {
    opt := option.WithCredentialsFile("key.json")
    ctx := context.Background()
    app, err := firebase.NewApp(ctx, nil, opt)
    if err != nil {
        fmt.Errorf("error initializing app: %v", err)
    }
    client, err := app.Firestore(ctx)
    if err != nil {
        fmt.Errorf("error initializing client: %v", err)
    }
    defer client.Close()
    fmt.Println("Connection done")
}

値の取得

package main

import (
	"fmt"

	"golang.org/x/net/context"

	firebase "firebase.google.com/go"
	"google.golang.org/api/option"
)

func main() {
    // クライアント接続
    opt := option.WithCredentialsFile("key.json")
    ctx := context.Background()
    app, err := firebase.NewApp(ctx, nil, opt)
    if err != nil {
        fmt.Errorf("error initializing app: %v", err)
    }
    client, err := app.Firestore(ctx)
    if err != nil {
        fmt.Errorf("error initializing client: %v", err)
    }
    defer client.Close()
    fmt.Println("Connection done")

    // 値の取得
    collection := client.Collection("コレクションID")
    doc := collection.Doc("ドキュメントID")
    field, err := doc.Get(ctx)
    if err != nil {
        fmt.Errorf("error get data: %v", err)
    }
    data := field.Data()
    for key, value := range data {
        fmt.Printf("key: %v, value: %v\n", key, value)
    }
}
5
2
1

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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?