1
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 3 years have passed since last update.

AtreugoでGo標準搭載のテンプレートエンジンを使う

Posted at

※主に備忘録で書いているので至らない点があることをご了承ください

まずAtreugoって何?

Qiitaの検索で掛けても引っかからなかったのでとりあえず説明入れておきます。

AtreugoはGo言語向けのウェブフレームワークです。
fasthttpをベースとして開発されています。
https://github.com/savsgio/atreugo

TechEmpowerが掲載しているWeb Framework Benchmark Round 20では、Go言語内では上位にランクインしています。
https://www.techempower.com/benchmarks/#section=data-r20&hw=ph&test=fortune&l=zijocf-sf

本題

テンプレートとソースコードは同じディレクトリとします。

template.tpl
<h1>Template is works!</h1>
<p>Now: {{ .Now }}</p>
main.go
package main

import (
	"github.com/savsgio/atreugo/v11"
	"text/template"
	"time"
)

func main() {
	config := atreugo.Config{
		Addr: "127.0.0.1:8000"
	}
	server := atreugo.New(config)
	app.GET("/", renderIndex)

	if err := app.ListenAndServe(); err != nil {
		panic(err)
	}
}

func renderIndex(ctx *atreugo.RequestCtx) error {
	tpl := template.Must(template.ParseFiles("template.tpl"))
	data := map[string]string{
		"Now": time.Now().Format("2006-01-02 15:04:05"),
	}
	ctx.SetContentType("text/html")
	return tpl.Execute(ctx, nil)
}

テンプレートのExecute関数にそのまま*atreugo.RequestCtxを入れるだけでOKでした。
*atreugo.RequestCtxio.Writerのインターフェースを満たしているため)
ただ、ctx.SetContentTypeを設定してあげないとそのまま書かれてしまうので、text/htmlを入れてHTMLファイルとして認識してもらうようにします。

HTTPステータスコードを変えるときはctx.Response.Header.SetStatusCodeを関数内に入れればOK。

結論

  • Executeの第一引数に*atreugo.RequestCtxを入れる
  • ctx.SetContextTypeでテンプレートに応じた形式にしておく
  • ステータスコードを変えるときはctx.Response.Header.SetStatusCodeを関数を用いる
1
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
1
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?