※主に備忘録で書いているので至らない点があることをご了承ください
まず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
本題
テンプレートとソースコードは同じディレクトリとします。
<h1>Template is works!</h1>
<p>Now: {{ .Now }}</p>
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.RequestCtx
はio.Writer
のインターフェースを満たしているため)
ただ、ctx.SetContentType
を設定してあげないとそのまま書かれてしまうので、text/html
を入れてHTMLファイルとして認識してもらうようにします。
HTTPステータスコードを変えるときはctx.Response.Header.SetStatusCode
を関数内に入れればOK。
結論
-
Execute
の第一引数に*atreugo.RequestCtx
を入れる -
ctx.SetContextType
でテンプレートに応じた形式にしておく - ステータスコードを変えるときは
ctx.Response.Header.SetStatusCode
を関数を用いる