ライブラリーのインストール
go get firebase.google.com/go
firestore_create.go
// ---------------------------------------------------------------
//
// firestore_create.go
//
// Dec/16/2020
//
// ---------------------------------------------------------------
package main
import (
"context"
"fmt"
"log"
"os"
"reflect"
"cloud.google.com/go/firestore"
firebase "firebase.google.com/go"
"google.golang.org/api/option"
)
// ---------------------------------------------------------------
func data_set_proc(client *firestore.Client,ctx context.Context,
key_in string, name_in string, population_in int, date_mod string) {
_, err := client.Collection("cities").Doc(key_in).Set(ctx, map[string]interface{}{
"name": name_in,
"population": population_in,
"date_mod": date_mod,
})
if err != nil {
log.Fatalf("Failed adding alovelace: %v", err)
}
}
// ---------------------------------------------------------------
func main() {
fmt.Fprintf (os.Stderr,"*** 開始 ***\n")
// 初期化
ctx := context.Background()
sa := option.WithCredentialsFile("./application_default_credentials.json")
app, err := firebase.NewApp(ctx, nil, sa)
if err != nil {
log.Fatalln(err)
}
client, err := app.Firestore(ctx)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("%T\n", client)
fmt.Printf("%T\n", ctx)
fmt.Println(reflect.TypeOf(client))
fmt.Println(reflect.TypeOf(ctx))
data_set_proc(client,ctx,"t0921","宇都宮",49572,"1921-7-19")
data_set_proc(client,ctx,"t0922","小山",63452,"1921-7-19")
data_set_proc(client,ctx,"t0923","佐野",63452,"1921-7-19")
data_set_proc(client,ctx,"t0924","足利",63452,"1921-7-19")
data_set_proc(client,ctx,"t0925","日光",63452,"1921-7-19")
data_set_proc(client,ctx,"t0926","下野",41528,"1921-7-19")
// 切断
defer client.Close()
fmt.Fprintf (os.Stderr,"*** 終了 ***\n")
}
// ---------------------------------------------------------------
実行コマンド
project_id="project-dec16-2020"
echo $project_id
export GOOGLE_CLOUD_PROJECT=$project_id
#
go run firestore_create.go