LoginSignup
0
0

Go言語で作ったPubSub起動のCloud Functionsの関数をローカル環境(Mac)で動かす

Posted at

概要

PubSubのイベントを受け取って起動するGo言語で作った Cloud Functions の関数をローカル環境で実行する方法

参考

事前準備

  • goのversionを1.18に上げておく(ここでハマったので)
  • gcloud auth application-default login でログインしておく

方法

ディレクトリ構成

.
├── cmd
│   └── main.go
├── go.mod
├── go.sum
└── hoge_functions.go

起動関数(main.go)

package main

import (
	"fmt"
	"github.com/GoogleCloudPlatform/functions-framework-go/funcframework"
	"github.com/hogehoge/fugafuga/sample/hoge"
	"log"
)

func main() {
	funcframework.RegisterEventFunction("/", hoge.HogeFunction) // ここで自作したCloud Functionsの関数を呼ぶ
	port := "8080"
	if err := funcframework.Start(fmt.Sprintf("%s", port)); err != nil {
		log.Fatalf("funcframework.Start: %v\n", err)
	}
}

実行

GOOGLE_CLOUD_PROJECT="your-project-id" go run ./cmd/main.go

確認方法

ローカル関数を呼び出す  |  Google Cloud Functions に関するドキュメント にあるとおり、curlで確認する

d29ybGQ=がデータの中身(base64)になるらしいです。topic名は特に変更することなく動きました。パスが合ってればいいんでしょうね。おそらく。

# 'world' base64-encoded is 'd29ybGQ='
curl localhost:8080 \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
        "context": {
          "eventId":"1144231683168617",
          "timestamp":"2020-05-06T07:33:34.556Z",
          "eventType":"google.pubsub.topic.publish",
          "resource":{
            "service":"pubsub.googleapis.com",
            "name":"projects/sample-project/topics/gcf-test",
            "type":"type.googleapis.com/google.pubsub.v1.PubsubMessage"
          }
        },
        "data": {
          "@type": "type.googleapis.com/google.pubsub.v1.PubsubMessage",
          "attributes": {
             "attr1":"attr1-value"
          },
          "data": "d29ybGQ="
        }
      }'
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