LoginSignup
90
71

More than 5 years have passed since last update.

Cloud FunctionsにGoがサポートされたので使ってみた

Last updated at Posted at 2019-01-17

GCPのCloud Functionsでgolangがサポートされました。
Cloud Functions: Go 1.11 is now a supported language | Google Cloud Blog

さっそく使ってみたいと思います。

導入

gcloudが必要なのでインストールしておきます。
また現在Golangのサポートはベータなので、gcloudでベータ機能を使えるようにしておきます。

$ gcloud components update
$ gcloud components install beta

今回作るサンプルのプロジェクトを作成します。

$ mkdir sample-cloudfunctions-go && cd sample-cloudfunctions-go

Cloud Functionsでgolangを使う場合、Go Modulesが必要です。
golang1.11では環境変数で宣言が必要です。

$ export GO111MODULE=on
$ # 以下コマンドでgo.modファイルが作成される
$ go mod init

サンプルの関数を作ります。

function.go
package sample

import "net/http"

func Hello(w http.ResponseWriter, r *http.Request) {
    msg := "Hello World"
    w.Write([]byte((msg)))
}

デプロイします。

$ gcloud functions deploy Hello --runtime go111 --trigger-http
# 以下一部抜粋
Deploying function (may take a while - up to 2 minutes)...done.
availableMemoryMb: 256
entryPoint: Hello
httpsTrigger:
  url: https://us-central1-xxxxxxxxx.cloudfunctions.net/Hello
labels:
  deployment-tool: cli-gcloud
name: projects/xxxxxxxxx/locations/us-central1/functions/Hello
runtime: go111
status: ACTIVE
timeout: 60s
updateTime: '2019-01-17T00:28:43Z'
versionId: '1'

トリガーするURLが出力されるので叩いてみると・・・

$ curl https://us-central1-xxxxxxxxx.cloudfunctions.net/Hello
Hello World

実行できました!

所感

net/http を使ってるのでとてもシンプルです。
どこかでmain関数を定義すればローカルでも実行できるため開発しやすいです。

cmd/main.go
package main

import (
    sample "github.com/morix1500/sample-cloudfunctions-go"
    "net/http"
)

func main() {
    http.HandleFunc("/hello", sample.Hello)
    http.ListenAndServe(":8082", nil)
}
$ echo "module github.com/morix1500/sample-cloudfunctions-go" > go.mod
$ go run cmd/main.go
$ curl localhost:8082/hello
Hello World

参考資料

The Go Runtime

90
71
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
90
71