@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Cloud Functions と Cloud Run を試した

公式のチュートリアルに従ってサンプルをそのままデプロイしただけ。

どういうものかをつかむために触ってみる目的だったので、とりあえずこんなもので十分。

Cloud Functions

  • エンドポイント一つに関数一つが対応する。シンプル。

Cloud Run

  • こっちはまだちょっとよくわかっていない
  • エンドポイント一つに Docker コンテナ一つが対応する?
  • Docker コンテナが提供するサービスが複数のエンドポイントを持つ場合は、 Cloud Run が提供するエンドポイント URL が Base URL のようになるんだろうか?
  • それとも / へのアクセスしかアプリケーションにはルーティングされない?
  • 自前のコンテナをデプロイするチュートリアルのコードを修正すれば実験できそう
  • 実験してみた結果、 Cloud Run では一つのアプリケーションで複数のルーティングを提供できる!

//ping の二つのルーティングを持つアプリケーション

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func handler(w http.ResponseWriter, r *http.Request) {
    log.Print("helloworld: received a request")
    target := os.Getenv("TARGET")
    if target == "" {
        target = "World"
    }
    fmt.Fprintf(w, "Hello %s!\n", target)
}

func pingHandler(w http.ResponseWriter, r *http.Request) {
    log.Print("ping: received a request")
    fmt.Fprintf(w, "Ping Pong\n")

}

func main() {
    log.Print("helloworld: starting server...")

    http.HandleFunc("/", handler)
    http.HandleFunc("/ping", pingHandler)

    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    log.Printf("helloworld: listening on port %s", port)
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
➜  helloworld-go curl -i https://helloworld-eda73rftvq-an.a.run.app/             
HTTP/2 200 
content-type: text/plain; charset=utf-8
date: Sun, 14 Jun 2020 19:05:10 GMT
server: Google Frontend
content-length: 13
alt-svc: h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"

Hello World!
➜  helloworld-go curl -i https://helloworld-eda73rftvq-an.a.run.app/ping
HTTP/2 200 
content-type: text/plain; charset=utf-8
date: Sun, 14 Jun 2020 19:05:12 GMT
server: Google Frontend
content-length: 10
alt-svc: h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"

Ping Pong