はじめに
GAEをGinを利用して構築していきます。
プロジェクトとアプリケーションの設定 (GAE/Go/Gin)の続きです。
流れは、公式サイトの静的コンテンツの配信と同じです。
ソース
今回のフォルダ構成は、以下の通りです。
svgファイルは、公式サイトからダウンロードしてください。
├──  template
│    └── index.html
├──  static
│    ├── style.css
│    └── gcp-gopher.svg
├──  app.yaml
└──  main.go
app.yaml
runtime: go111
handlers:
- url: /static
  static_dir: static
  
- url: /.*
  script: auto
style.css
body {
    font-family: Arial, sans-serif;
    color: blue;
  }
main.go
package main
import (
	"net/http"
	"github.com/gin-gonic/gin"
	"google.golang.org/appengine"
)
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>
      <link rel="stylesheet" type="text/css" href="/static/style.css">
  </head>
  <body>
    test
    <img id="logo" src="/static/gcp-gopher.svg" width="100">
    <h1>{{ .hello }}</h1>
  </body>
</html>
{{ end }}
ローカルで実行
dev_appserver.py app.yaml
localhost:8080  にアクセスすると以下の画面が表示されます。
アプリケーションをデプロイする
gcloud app deploy
アプリケーションを表示する
gcloud app browse
その後、http://[YOUR_PROJECT_ID].appspot.comで、画面が表示されるかを確認します。
