1. 程式人生 > 實用技巧 >golang mustache 模版引擎試用

golang mustache 模版引擎試用

主要是學習一個golang 的mustache模版引擎
cbroglie/mustache 是一個很不錯的golang mustache 模版引擎,支援的功能還是比較多的,
以下是一個簡單的使用

參考程式碼

  • go.mod
module demoapp
go 1.15
require (
  github.com/Jeffail/tunny v0.0.0-20181108205650-4921fff29480 // indirect
  github.com/cbroglie/mustache v1.2.0 // indirect
  github.com/stretchr/signature v0.0.0-20160104132143-168b2a1e1b56 // indirect
  github.com/stretchr/stew v0.0.0-20130812190256-80ef0842b48b // indirect
  github.com/stretchr/tracer v0.0.0-20140124184152-66d3696bba97 // indirect
)
  • main.go
package main
import (
  "log"
  "net/http"
  _ "net/http/pprof"
  "github.com/Jeffail/tunny"
  "github.com/cbroglie/mustache"
  "github.com/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 可以方便測試效能
  • 執行效果

參考資料

https://github.com/rongfengliang/mustache-tunny-learning
https://mustache.github.io/mustache.5.html
https://github.com/cbroglie/mustache
https://github.com/Jeffail/tunny