GoのWebフレームワーク Echoの "Template Rendering" を利用してHTMLページを作成する
はじめに
本ブログで goのwebフレームワーク "Echo" を利用して APIを作成してきました。Echoでいくつかページを作成したかったので"Template Rendering" を利用して htmlページを作成しました。
- 以前のEchoでAPIを作成したときの記事例
EchoのTemplate Renderingを使う
- ディレクトリ構成
- view/配下に top.htmlを配置
- handler/配下 top.goを配置してhtmlに表示するデータを定義しました。
├── README.md ├── go.mod ├── go.sum ├── handler │ └── top.go ├── main.go ├── staticcheck.conf └── view └── top.html
- main.go(一部抜粋)
package main import ( "io" "net/http" "text/template" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/yhidetoshi/apiEchoGAE-local/handler" ) var e = createMux() func createMux() *echo.Echo { e := echo.New() return e } type TemplateRender struct { templates *template.Template } func (t *TemplateRender) Render(w io.Writer, name string, data interface{}, c echo.Context) error { return t.templates.ExecuteTemplate(w, name, data) } func main() { // Echoインスタンス作成 // http.Handle("/", e) e.Use(middleware.Logger()) e.Use(middleware.Recover()) e.Use(middleware.Gzip()) // Template renderer := &TemplateRender{ templates: template.Must(template.ParseGlob("view/*.html")), } e.Renderer = renderer // ルーティング // // HTMLページ e.GET("/", handler.ShowTopHTML) e.Start(":8080") }
- view/top.html
{{define "top"}} <h1> <div>Go Echoで実装したAPIサービス</div> </h1> <li>APIリスト</li> <ul> <li>{{.ContentA}}</li> <li>{{.ContentB}}</li> <li>{{.ContentC}}</li> <li>{{.ContentD}}</li> </ul> {{end}}
- handler/top.go
package handler import ( "net/http" "github.com/labstack/echo/v4" ) func ShowTopHTML(c echo.Context) error { topData := map[string]string{ "ContentA": "投資信託のデータ取得", "ContentB": "金価格のデータを取得", "ContentC": "Coincheckの取引価格を取得", "ContentD": "GMOコインの取引価格を取得", } return c.Render(http.StatusOK, "top", topData) }
実行結果
ブラウザで確認 http://127.0.0.1:8080/
❯ curl localhost:8080 <h1> <div>Go Echoで実装したAPIサービス</div> </h1> <li>APIリスト</li> <ul> <li>投資信託のデータ取得</li> <li>金価格のデータを取得</li> <li>Coincheckの取引価格を取得</li> <li>GMOコインの取引価格を取得</li> </ul>
さいごに
簡単なページですが、"Template Rendering" を利用してページを作成しました。Goでhtmlページを作成したのはこれがはじめてでした。 次は DBを用意してDBマイグレーション、サインアップやログイン機能を実装していければと思います。