1
0

More than 3 years have passed since last update.

【Go】echoを使ってさくっとRoutingとTemplateを使いこなす

Last updated at Posted at 2020-04-28

はじめに

Goはインストールしてあるものとします。

REST APIを作りたい場合はこちらを参考にしてみてください。
【Go】echoを使ってさくっとAPIサーバを構築する

準備

ディレクトリ構成

(任意のディレクトリ)
|- views
    |-index.html
|- server.go
|- index.go

echoをインストール

echoをインストールします。

$ go get -u github.com/labstack/echo

実装

以下のように記述していきます。
initRoutingやinitTemplateはmain関数の中にまとめて記載しても問題ありませんが、分けておくとわかりやすいかと思います。

routingを増やしたかったら、

  • initRoutingの中に e.GET("/", hoge) と一行追記
  • hoge関数を作成
  • htmlファイルを作成

するだけなので簡単ですね。

server.go
package main

import (
    "html/template"
    "io"

    "github.com/labstack/echo"
)

func main() {
    e := echo.New()
    initRouting(e)
    e.Logger.Fatal(e.Start(":1323"))
}

type Template struct {
    templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    return t.templates.ExecuteTemplate(w, name, data)
}

func initRouting(e *echo.Echo) {
    initTemplate(e)
    e.GET("/", index)
}

func initTemplate(e *echo.Echo) {
    t := &Template{
        templates: template.Must(template.ParseGlob("views/*.html")),
    }
    e.Renderer = t
}
index.go
package main

import (
    "net/http"

    "github.com/labstack/echo"
)

func index(c echo.Context) error {
    return c.Render(http.StatusOK, "index", "World")
}
index.html
{{define "index"}}
Hello, {{.}}!
{{end}}

実行

プロジェクト配下で以下のコマンドを実行。

go run .

http://localhost:1323/ にアクセスして「Hello, World!」と表示されることを確認。

参考

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