golang mustache 模版引擎试用
主要是学习一个golang 的mustache模版引擎
cbroglie/mustache 是一个很不错的golang mustache 模版引擎,支持的功能还是比较多的,
以下是一个简单的使用
参考代码
- go.mod
module demoapp
go 1.15
require (
/Jeffail/tunny v0.0.0-20181108205650-4921fff29480 // indirect
/cbroglie/mustache v1.2.0 // indirect
/stretchr/signature v0.0.0-20160104132143-168b2a1e1b56 // indirect
/stretchr/stew v0.0.0-20130812190256-80ef0842b48b // indirect
/stretchr/tracer v0.0.0-20140124184152-66d3696bba97 // indirect
)
- main.go
package main
import (
"log"
"net/http"
_ "net/http/pprof"
"/Jeffail/tunny"
"/cbroglie/mustache"
"/stretchr/stew/objects"
)
// default demo content
const (
paylaod = `{
"name": "Alice",
"age":333,
"users":[
{
"name":"dalong",
"age":"333"
}
]
}`
)
func main() {
pool := tunny.NewFunc(1000, func(payload interface{}) interface{} {
log.Println(string(payload.([]byte)))
jsonmap, err := objects.NewMapFromJSON(string(payload.([]byte)))
if err != nil {
log.Println(err)
return nil
}
data, err := mustache.RenderFileInLayout("app.mustache", "layout.mustache", jsonmap.MSI())
if err != nil {
log.Println(err)
return nil
}
log.Println(data)
return data
})
defer pool.Close()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
result := pool.Process([]byte(paylaod))
if result != nil {
msg := result.(string)
w.Write([]byte(msg))
return
}
w.Write([]byte("unknow"))
})
http.ListenAndServe(":8080", nil)
}
- 默认
app.mustache
<h1>{{name}}-{{age}}</h1>
<ul>
{{#users}}
<li>
-{{name}}
-{{age}}
</li>
{{/users}}
</ul>
layout.mustache
<html>
<head><title>Hi</title></head>
<body>
{{{content}}}
</body>
</html>
- 简单说明
以上是一个集成了模版的使用demo,因为需要json 数据,所以直接基于了一个工具类stretchr/stew 转换
json string 为map,同时使用了Jeffail/tunny 以恶搞goroutine 包,集成了pprof 可以方便测试性能 - 运行效果