0
1

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 5 years have passed since last update.

GoでDatastoreからKeyを指定して特定Entityを取ってくる

Last updated at Posted at 2019-06-30

AppEngine等用意しなくてもgoの実行環境だけで、DatastoreからKeyを指定して特定Entityの中身をJSONで表示する

事前に用意するもの

・goの実行環境
・Datastoreユーザ権限のあるサービスアカウントのJSONファイル

datastoreライブラリ導入
go get cloud.google.com/go/datastore

Entity取得(プログラム内のKind構造体は、各環境に合わせる)

getDatastoreEntity.go
// DatastoreのKeyを指定して、Entityの中身を表示(JSON)
// 引数(左から順に):プロジェクトID サービスアカウントの鍵 Kind Key
// コマンド例) $ go run getDatastoreEntity.go datastore-project-id service-account.json country JPN
package main

import (
	"context"
	"os"
	"cloud.google.com/go/datastore"
	"fmt"
	"flag"
	"encoding/json"
)

// Datastoreの各Kindを構造体定義
type City struct {
	CountryCode		string
	District		string
	Population		int
}
type Country struct {
	Continent	string
	Name		string
	Region		string
}

func main() {
	flag.Parse()
	projectId := flag.Arg(0)
	serviceKey := flag.Arg(1)
	kind := flag.Arg(2)
	key := flag.Arg(3)
	
	// DatastoreのプロジェクトID、サービスアカウントの鍵設定
	ctx := context.Background()
	os.Setenv("DATASTORE_PROJECT_ID", projectId)
	os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", serviceKey)
	dsClient, _ := datastore.NewClient(ctx, projectId)
	
	// 各Kindを初期化
	city := new(City)
	country := new(Country)
	
	// (GQL) select * from Kind where __key__ = KEY(Kind, Key)
	dk := datastore.NameKey(kind, key, nil)
	jsonBytes := []byte{}
	switch kind { 
		case "city": 
			dsClient.Get(ctx, dk, city)
			jsonBytes, _ = json.Marshal(city)
		default: 
			dsClient.Get(ctx, dk, country)
			jsonBytes, _ = json.Marshal(country)
	}
	jsonStr := string(jsonBytes)
	fmt.Println(jsonStr)
}
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?