From d8f76c01d0f36919d6509d8d65c3d193abce4d33 Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Sat, 22 Oct 2016 14:34:33 +0900 Subject: [PATCH] Template parsing --- main.go | 38 ++++++++++++++++++++++++++++++++++++-- pages/anime/anime.pug | 8 ++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 440cf9e2..9604031d 100644 --- a/main.go +++ b/main.go @@ -1,21 +1,35 @@ package main import ( + "fmt" + "io" + "reflect" "strconv" + "strings" + "github.com/Joker/jade" "github.com/aerojs/aero" "github.com/animenotifier/arn" "github.com/buaazp/fasthttprouter" "github.com/valyala/fasthttp" + "github.com/valyala/fasttemplate" ) func main() { arn.Init() app := aero.New() + jade.PrettyOutput = false + code, _ := jade.ParseFile("pages/anime/anime.pug") + code = strings.TrimSpace(code) + code = strings.Replace(code, "{{ ", "{{", -1) + code = strings.Replace(code, " }}", "}}", -1) + fmt.Println(code) + t := fasttemplate.New(code, "{{", "}}") app.Get("/", func(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) { - ctx.Write(ctx.RequestURI()) + ctx.Response.Header.Set("content-type", "text/html;charset=utf-8") + ctx.SetBodyString("Hello World") }) app.Get("/anime/:id", func(ctx *fasthttp.RequestCtx, params fasthttprouter.Params) { @@ -27,8 +41,28 @@ func main() { return } - ctx.WriteString(anime.Description) + ctx.Response.Header.Set("content-type", "text/html;charset=utf-8") + + writer := ctx.Response.BodyWriter() + t.ExecuteFunc(writer, func(w io.Writer, tag string) (int, error) { + val := reflect.ValueOf(*anime) + parts := strings.Split(tag, ".") + + for _, part := range parts { + val = val.FieldByName(part) + } + + switch val.Kind() { + case reflect.Int: + num := strconv.FormatInt(val.Int(), 10) + return w.Write([]byte(num)) + default: + return w.Write([]byte(val.String())) + } + }) }) + fmt.Println("Starting server on http://localhost:5000/") + app.Run() } diff --git a/pages/anime/anime.pug b/pages/anime/anime.pug index bef663e1..53939c8d 100644 --- a/pages/anime/anime.pug +++ b/pages/anime/anime.pug @@ -1,2 +1,6 @@ -h1 {{.Title.Romaji}} -p {{.Description}} \ No newline at end of file +h1 {{ Title.Romaji }} +p {{ Description }} +if ID + p {{ ID }} +else + p Undefined. \ No newline at end of file