2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

プロジェクトとアプリケーションの設定 (GAE/Go/Gin)

Last updated at Posted at 2019-07-07

#はじめに
GAEをGinを利用して構築していきます。
流れは、公式サイトのプロジェクトとアプリケーションの設定と同じです。

#環境設定(SDKのインストール)

##前提
GCPのアカウント登録、GAEのプロジェクト作成、Goのインストールをしておいてください。
Goのバージョンは、1.11を利用しています。

SDKのインストールは、公式サイトの通りに行います。
Google Cloud SDK のドキュメント

#ソース

今回のフォルダ構成は、以下の通りです。

├──  template
│    └── index.html
├──  app.yaml
└──  main.go
app.yaml
runtime: go111

handlers:
- url: /.*
  script: auto
main.go
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"google.golang.org/appengine"
)

// init は古い
func main() {
	router := gin.Default()

	router.LoadHTMLGlob("template/*") // 事前にテンプレートをロード(相対パス)

	router.GET("/", HelloWorld)

	http.Handle("/", router) // router.Run(":8080")の代わり
	appengine.Main()         // これがないと動かない
}

func HelloWorld(c *gin.Context) {
	c.HTML(http.StatusOK, "top/hello", gin.H{
		"hello": "hello, World!!",
	})
}
template/index.html
{{ define "top/hello" }}
<!DOCTYPE html>
<html>
  <head>
  </head>

  <body>
    test
    <h1>{{ .hello }}</h1>
  </body>
</html>
{{ end }}

#ローカルで実行
dev_appserver.py app.yaml

この時、pythonが2系以外だと、以下のエラーが発生します。

ERROR: Python 3 and later is not compatible with the Google Cloud SDK. Please use Python version 2.7.x.

If you have a compatible Python interpreter installed, you can use it by setting
the CLOUDSDK_PYTHON environment variable to point to it.

2系と3系の共存は、以下のサイトを参考にしました。
Python 2系と3系の共存

localhost:8080 にアクセスすると以下の画面が表示されます。

スクリーンショット 2019-07-07 13.32.59.png

#アプリケーションをデプロイする

gcloud app deploy

以下のエラーが発生した場合、SDKの初期化がされていませんので、初期化を行います。

ERROR: (gcloud.app.deploy) INTERNAL: Internal error encountered.

##SDKの初期化
gcloud init

3回ほど質問されるが、基本的に「1」を選択して問題ないと思います。

#アプリケーションを表示する

gcloud app browse

起動確認が入るので、[Y]を選択します。

その後、http://[YOUR_PROJECT_ID].appspot.comで、画面が表示されるかを確認します。

#参考
プロジェクトとアプリケーションの設定

Python 2系と3系の共存

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?