[A-00190]golangでCloudFunctionsを動かしてみる

golangを使ってCloudFunctionsを動かしてみたいと思います。

・とりあえずHello,Worldやってみる

一番簡単なやつをやってみたいと思います。

適当なプロジェクトを作成します。

mkdir helloworld

次にhello_http.goを作成します。

package helloworld

import (
"encoding/json"
"fmt"
"html"
"net/http"

"github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

func init() {
functions.HTTP("HelloHTTP", HelloHTTP)
}

// HelloHTTP is an HTTP Cloud Function with a request parameter.
func HelloHTTP(w http.ResponseWriter, r *http.Request) {
var d struct {
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
fmt.Fprint(w, "Hello, World!")
return
}
if d.Name == "" {
fmt.Fprint(w, "Hello, World!")
return
}
fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
}

次に依存関係の解決をします。

go mod init example.com/hello
go mod tidy

上記を実行後、下記の通りになります。cmdディレクトリ配下は作成しなくて大丈夫です。

上記を作成後、下記のgcloudコマンドでCloudFunctionsにデプロイします。

  gcloud functions deploy go-http-function \
--gen2 \
--runtime=go121 \
--region=asia-northeast1 \
--source=. \
--entry-point=HelloHTTP \
--trigger-http \
--allow-unauthenticated

実行後、下記の通りデプロイされれば完了です。

HTTP-endpointにリクエストを飛ばしてテスト実行してみます。

curl https://asia-northeast1-your-project.cloudfunctions.net/go-http-function
$ curl https://asia-northeast1-my-jp-test.cloudfunctions.net/go-http-function
Hello, World!

上記で完了です。

・BigQueryにデータを挿入してみる

次にDWHとの連携プログラムを作りたいと思います。

Bigquery上に下記のような単純なテーブルを作成しておきます。ここではmy_dataset.my_tableというものを作成しています。

Appendix

公式サイトはこちら

https://cloud.google.com/functions/docs/create-deploy-http-go?hl=ja

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

*