GAEのGoでHelloWorld
概要
GCPにいろんなサービスが存在するのはわかったが
とりあえずBookshelfプリケーション作ろうチュートリアル に準じて一通りのサービスを触ってみる。まずはGAE(Go1.12)でHelloWorldしてみるのだ。
ちなみに実験環境は「mac OS Mojave 10.14.6」
事前準備
ブラウザのコンソールよりターミナルからコマンドで実行できた方がかっこいいので
Cloud SDK のインストール に準じてgcloudが実行できる環境を準備
gcloudコマンドのインストール
まずインストール。何か聞かれたら基本「Y」か「何も書かず」Enter
curl https://sdk.cloud.google.com | bash
シェルを再起動
exec -l $SHELL
gcloud環境を初期化。希望するgoogleアカウントでログイン。
gcloud init # [1] Re-initialize this configuration [default] with new settings # [3] Log in with a new account # [1] abstract-hydra-251604
構築
プロジェクトを作ってみよう
ざっとドキュメント見てみたところ
「組織->フォルダ->プロジェクト->GCEとかBigQueryとかいろんなサービス達」こんな構成にできるらしい。
でも組織、フォルダは「G Suite」か「Cloud Identity」契約してないとダメらしい。。
「ucwork->open or private->ucwork-ai-000001->サービス達」こんな感じにしてみたかったけど・・取り急ぎプロジェクトのみで行こう
プロジェクトの新規作成
gcloud projects create ucwork-ai-000002 --name="gae hello world" Create in progress for [https://cloudresourcemanager.googleapis.com/v1/projects/ucwork-ai-000002]. Waiting for [operations/cp.6028126867139483180] to finish...done. Enabling service [cloudapis.googleapis.com] on project [ucwork-ai-000002]... Operation "operations/acf.b0ff89af-10b4-4f38-8221-d4da7b79c559" finished successfully.
プロジェクト一覧確認
gcloud projects list
PROJECT_ID NAME PROJECT_NUMBER
ucwork-ai-000002 gae hello world 298968203397
プロジェクトの詳細
gcloud projects describe ucwork-ai-000002 createTime: '2019-09-23T08:05:31.373Z' lifecycleState: ACTIVE name: gae hello world projectId: ucwork-ai-000002 projectNumber: '298968203397'
デフォルトプロジェクトの確認
デフォルトプロジェクトの設定を確認。
違うプロジェクトが設定されている。さっき作成したプロジェクトをセットしよー
gcloud config list [core] account = [your gmail account] disable_usage_reporting = False project = ucwork-ai-000001 Your active configuration is: [default]
デフォルトプロジェクト設定
さっき作成したプロジェクトをデフォルトプロジェクトに設定
gcloud config set project ucwork-ai-000002
Updated property [core/project].
[core]
account = [your gmail account]
disable_usage_reporting = False
project = ucwork-ai-000002
Your active configuration is: [default]
GAE用のアプリケーション作成
GoでHelloWorldなアプリケーション作成
モデュール初期化
go mod init github.com/shintaro123/ucwork-go
8080ポートの/でアクセスがあった場合のみHelloWorldなアプリケーション
package main import ( "fmt" "log" "net/http" "os" ) func main() { http.HandleFunc("/", indexHandler) port := os.Getenv("PORT") if port == "" { port = "8080" log.Printf("Defaulting to port %s", port) } log.Printf("Listening on port %s", port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)) } func indexHandler(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } fmt.Fprint(w, "Hello, World!") }
ローカルで実行させてみる
以下の通り実行して
ブラウザでhttp://localhost:8080/
実行すると「Hello, World!」表示されました。
go build ./ucwork-go 2019/09/23 17:32:19 Defaulting to port 8080 2019/09/23 17:32:19 Listening on port 8080
GAEアプリケーションのデプロイ
GAEへのデプロイ条件指示ファイル作成
app.yamlファイル作成
ランタイムだけ指定しとく
runtime: go112
デプロイ実行
デプロイ!
[2] asia-northeast1を選択じゃ!
gcloud app deploy [add_hello_world] You are creating an app for project [ucwork-ai-000002]. WARNING: Creating an App Engine application for a project is irreversible and the region cannot be changed. More information about regions is at <https://cloud.google.com/appengine/docs/locations>. Please choose the region where you want your App Engine application located: [1] asia-east2 (supports standard and flexible) [2] asia-northeast1 (supports standard and flexible) [3] asia-northeast2 (supports standard and flexible) [4] asia-south1 (supports standard and flexible) [5] australia-southeast1 (supports standard and flexible) [6] europe-west (supports standard and flexible) [7] europe-west2 (supports standard and flexible) [8] europe-west3 (supports standard and flexible) [9] europe-west6 (supports standard and flexible) [10] northamerica-northeast1 (supports standard and flexible) [11] southamerica-east1 (supports standard and flexible) [12] us-central (supports standard and flexible) [13] us-east1 (supports standard and flexible) [14] us-east4 (supports standard and flexible) [15] us-west2 (supports standard and flexible) [16] cancel Please enter your numeric choice: 2 Creating App Engine application in project [ucwork-ai-000002] and region [asia-northeast1]....done. Services to deploy: descriptor: [/Users/shintaro.a.uchiyama/project/github.com/shintaro123/ucwork-go/app.yaml] source: [/Users/shintaro.a.uchiyama/project/github.com/shintaro123/ucwork-go] target project: [ucwork-ai-000002] target service: [default] target version: [20190923t175204] target url: [https://ucwork-ai-000002.appspot.com] Do you want to continue (Y/n)? Y Beginning deployment of service [default]... ╔════════════════════════════════════════════════════════════╗ ╠═ Uploading 11 files to Google Cloud Storage ═╣ ╚════════════════════════════════════════════════════════════╝ File upload done. Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [7] Access Not Configured. Cloud Build has not been used in project ucwork-ai-000002 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/cloudbuild.googleapis.com/overview?project=ucwork-ai-000002 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.
なんか怒られた...
何やらサービスがdisabledになってるらしいのでenableにしてみる
# サービスから名前絞ってみる gcloud services list --available | grep cloudbuild cloudbuild.googleapis.com Cloud Build API # 対象サービスをenabledにしてみる gcloud services enable cloudbuild.googleapis.com ERROR: (gcloud.services.enable) FAILED_PRECONDITION: Billing must be enabled for activation of service '[cloudbuild.googleapis.com, containerregistry.googleapis.com]' in project '298968203397' to proceed. - '@type': type.googleapis.com/google.rpc.PreconditionFailure violations: - description: "billing-enabled: Project's billing account is not found. https://console.developers.google.com/project/298968203397/settings" subject: '298968203397' type: serviceusage/billing-enabled
また怒られた...先は長いぜ
課金有効にしろ的な感じに見えるな
課金を有効化
課金アカウント一覧確認
gcloud alpha billing accounts list ACCOUNT_ID NAME OPEN MASTER_ACCOUNT_ID 0184D4-9DEE56-138D09 My Billing Account True
今回のプロジェクトに↑のアカウント紐づけてみよう
gcloud alpha billing projects link ucwork-ai-000002 --billing-account 0184D4-9DEE56-138D09 [add_hello_world]
billingAccountName: billingAccounts/0184D4-9DEE56-138D09
billingEnabled: true
name: projects/ucwork-ai-000002/billingInfo
projectId: ucwork-ai-000002
再度サービスを有効化じゃ!
gcloud services enable cloudbuild.googleapis.com [add_hello_world] Operation "operations/acf.5ad913ed-016f-455f-b2c9-c906e0d09d36" finished successfully.
うまくいった!!!この勢いでデプロイじゃ!
2度目の正直。デプロイ
うまくデプロイできた!!!
gcloud app deploy [add_hello_world] Services to deploy: descriptor: [/Users/shintaro.a.uchiyama/project/github.com/shintaro123/ucwork-go/app.yaml] source: [/Users/shintaro.a.uchiyama/project/github.com/shintaro123/ucwork-go] target project: [ucwork-ai-000002] target service: [default] target version: [20190923t195917] target url: [https://ucwork-ai-000002.appspot.com] Do you want to continue (Y/n)? y Beginning deployment of service [default]... ╔════════════════════════════════════════════════════════════╗ ╠═ Uploading 0 files to Google Cloud Storage ═╣ ╚════════════════════════════════════════════════════════════╝ File upload done. Updating service [default]...done. Setting traffic split for service [default]...done. Deployed service [default] to [https://ucwork-ai-000002.appspot.com] You can stream logs from the command line by running: $ gcloud app logs tail -s default To view your application in the web browser run: $ gcloud app browse
以下叩いてブラウザからアクセス!
無事Hello,Worldみれましたわ。
gcloud app browse [add_hello_world] Opening [https://ucwork-ai-000002.appspot.com] in a new tab in your default browser.
まとめ
「独自ドメインの場合どうするの」とか
「app.yamlの設定あんまり理解してない」とか色々あるけど欲張らずちょっとずつ進めてこう。
次はアプリケーションをNoSQLやSQLにつないでみたい