Go × Firebase Emulator で Firestore にデータを追加する
Firebase Firestore をローカルで安全に試したいときに便利なのが Firebase Emulator Suite。
Go(Golang)からも簡単に接続して、エミュレータ上の Firestore にデータ追加ができます。
今回は Docker 上で Firebase Emulator を起動し、Go から Firestore にデータを追加してみます。
リポジトリはこちら
こんな人にオススメ
- CLIをローカル環境に入れたくない
- FirestoreにGoで読み書きをしたい
- 料金気にせずにFirestoreをローカルで使いまわしたい
Docker環境構築
まずはDockerのファイルを作っていきます
FirebaseのDockerfile
FROM node:20.10.0-slim
RUN apt-get -y update && apt-get -y install default-jdk
RUN npm install -g firebase-tools
エミュレータを使うには、node.jsとJavaが必要みたいなのでインストールしておきます。
GoのDockerfile
# Golang 1.23の公式イメージを使用
FROM golang:1.23-alpine
# 作業ディレクトリを設定
WORKDIR /app
# キャッシュ利用で効率化するために別でコピー
COPY go.mod go.sum ./
RUN go mod download
# アプリケーションのソースコードをコピー
COPY . .
docker-compose.yml
services:
backend:
build: ./backend
tty: true
ports:
- 8888:8888
environment:
FIRESTORE_EMULATOR_HOST: "firebase:8080"
volumes:
- ./backend:/app
firebase:
build: ./firebase
ports:
- 4000:4000
- 8080:8080
volumes:
- ./firebase/.firebaserc:/firebase/.firebaserc
- ./firebase/firebase.json:/firebase/firebase.json
tty: true
working_dir: /firebase
command: firebase emulators:start
Firestoreエミュレータを使う場合FIRESTORE_EMULATOR_HOST
を環境変数に設定しないといけないみたいなので設定しておきます。
Firebaseの設定
次にエミュレータを使うのに必要なFirebaseの設定ファイルを2つ作成します
{
"projects": {
"default": "test-app-123456"
}
}
プロジェクト名はテスト用なのでなんでもいいです。
{
"emulators": {
"firestore": {
"host": "0.0.0.0",
"port": 8080
},
"ui": {
"enabled": true,
"host": "0.0.0.0",
"port": 4000
},
"singleProjectMode": false
}
}
これらのファイルはfirebase init
でプロジェクト初期化設定をすれば自動的に作られるんですが、今回はエミュレータを動かしたいだけなので普通に作ります。
Firestoreにデータを追加するGoを作成
コマンド叩けばFirestoreにテストデータを追加するGoのファイルを作ります
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client := createClient(ctx)
defer client.Close()
createSample(ctx, client)
}
func createClient(ctx context.Context) *firestore.Client {
projectID := "test-app-123456"
client, err := firestore.NewClient(ctx, projectID)
if err != nil {
fmt.Println("Failed to create client: %v")
}
return client
}
func createSample(ctx context.Context, client *firestore.Client) {
_, _, err := client.Collection("users").Add(ctx, map[string]interface{}{
"first": "test",
"last": "test",
"born": 1995,
})
if err != nil {
fmt.Println("Failed adding alovelace: %v")
}
}
エミュレータを起動
dockerを立ち上げます
docker compose up -d
しばらく経てばエミュレータが起動してhttp://localhost:4000にアクセスすればエミュレータのUIが見れます
データを入れてみる
先ほど作成したGoを実行してテストデータをFirestoreに追加します
docker compose exec backend go run cmd/main.go
実行後、http://localhost:4000/firestoreにアクセスするとusers
コレクションにドキュメントが追加されている
🧵 まとめ
Firebase Emulator を使えば、料金を気にせず・本番に影響せずに Firestore の動作検証ができるので、開発中のローカルテストにぴったりです。
Go でも公式SDKを使えば簡単に扱えるので、APIや管理ツールの試作におすすめです!
Discussion