
もくじ
関連
- GCP CLI設定 CloudFunctions+BigQuery+CloudRun+ESPv2+独自ドメイン①
- GCP BigQueryの作成 CloudFunctions+BigQuery+CloudRun+ESPv2+独自ドメイン②
- GCP CloudFunction 関数の作成 CloudFunctions+BigQuery+CloudRun+ESPv2+独自ドメイン③
- GCP CloudRun + ESPv2によるAPI Gatewayリバースプロキシの作成④ CloudFunctions+BigQuery+CloudRun+ESPv2+独自ドメイン



- ランタイム
 Go 1.13
- エントリーポイント
 StoreLoginHistory
function.go
// Package p contains an HTTP Cloud Function.
package p
import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"
	"context"
	"cloud.google.com/go/bigquery"
)
type Data struct {
	UserId int `bigquery:"user_id"`
	AnonymousToken string `bigquery:"anonymous_token"`
	LoginType string `bigquery:"login_type"`
	CreatedAt time.Time `bigquery:"created_at"`
}
// HelloWorld prints the JSON encoded "message" field in the body
// of the request or "Hello, World!" if there isn't one.
func StoreLoginHistory(w http.ResponseWriter, r *http.Request) {
	var d struct {
		Message string `json:"message"`
		UserId int `json:"user_id"`
		AnonymousToken string `json:"anonymous_token"`
		LoginType string `json:"login_type"`
	}
	if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
		switch err {
		case io.EOF:
			fmt.Fprint(w, "Hello World!")
			return
		default:
			log.Printf("json.NewDecoder: %v", err)
			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
			return
		}
	}
	if d.Message == "" {
		fmt.Fprint(w, "Hello World!")
		return
	}
    // コンテキストを取得する
    ctx := context.Background()
    // プロジェクトIDを取得する
    projectID := "test-cloud-functions-20211208"
    // BigQueryを操作するクライアントを作成する、エラーの場合はLoggingへ出力する
    client, err := bigquery.NewClient(ctx, projectID)
    if err != nil {
            log.Printf("BigQuery接続エラー Error:%T message: %v", err, err)
            return
    }
    // deferでクライアントを閉じる
    defer client.Close()
    // BigQuery用データ準備
	data := Data{}
	data.UserId = d.UserId
	data.AnonymousToken = d.AnonymousToken
	data.LoginType = d.LoginType
	data.CreatedAt = time.Now()
    //クライアントからテーブルを操作するためのアップローダーを取得する
    u := client.Dataset("test_dataset_kanehiro").Table("login_histories").Uploader()
    //テーブルへデータの追加を行う、エラーの場合はLoggingへ出力する
    err = u.Put(ctx, data)
    if err != nil {
            log.Printf("データ書き込みエラー Error:%T message: %v", err, err)
            return
    }
	// fmt.Fprint(w, html.EscapeString(d.LoginType))
	log.Printf("success")
	return
}

デプロイできた。
権限の設定

権限タブから、
- 新しいプリンシパル
 allusers
- ロール
 Cloud Functions起動元

これでWEBからアクセスできるようになりました
動作確認
- POST
- https://asia-northeast1-test-cloud-functions-20211208.cloudfunctions.net/storeLoginHistory
{
    "user_id": 999,
    "anonymous_token": "tokendayo1",
    "login_type": "Normal"
}
クエリで確認しよう
SELECT * FROM `test-cloud-functions-20211208.test_dataset_kanehiro.login_histories` LIMIT 1000

プレビューだとちゃんと表示されないので注意^^;;











![[Golang]defer実行順序](https://www.yuulinux.tokyo/contents/wp-content/uploads/2023/01/golang_logo_icon_171073-150x150.png)

