0
0

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: Cloud Firestore のデータを作成 (Create)

Posted at

ライブラリーのインストール

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
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?