valyala/fasttemplate

GitHub: valyala/fasttemplate

一个极简且高速的 Go 模板引擎,专注于将模板占位符替换为用户定义的值,在性能和内存分配上显著优于标准库方案。

Stars: 909 | Forks: 83

# fasttemplate 简单且快速的 Go 模板引擎。 Fasttemplate 仅执行一项任务——将模板占位符替换为用户定义的值。速度极快 :) 如果你需要快速且强大的 HTML 模板引擎,可以看看 [quicktemplate](https://github.com/valyala/quicktemplate)。 *请注意,与 [html/template](http://golang.org/pkg/html/template/) 不同,fasttemplate 不会对模板值进行任何转义处理。因此,在将值传递给 fasttemplate 之前,必须对其进行适当的转义。* 在占位符替换方面,Fasttemplate 比 [text/template](http://golang.org/pkg/text/template/)、 [strings.Replace](http://golang.org/pkg/strings/#Replace)、 [strings.Replacer](http://golang.org/pkg/strings/#Replacer) 和 [fmt.Fprintf](https://golang.org/pkg/fmt/#Fprintf) 都要快。 以下是将 fasttemplate 的性能与 text/template、strings.Replace、strings.Replacer 和 fmt.Fprintf 进行比较的基准测试结果: ``` $ go test -bench=. -benchmem PASS BenchmarkFmtFprintf-4 2000000 790 ns/op 0 B/op 0 allocs/op BenchmarkStringsReplace-4 500000 3474 ns/op 2112 B/op 14 allocs/op BenchmarkStringsReplacer-4 500000 2657 ns/op 2256 B/op 23 allocs/op BenchmarkTextTemplate-4 500000 3333 ns/op 336 B/op 19 allocs/op BenchmarkFastTemplateExecuteFunc-4 5000000 349 ns/op 0 B/op 0 allocs/op BenchmarkFastTemplateExecute-4 3000000 383 ns/op 0 B/op 0 allocs/op BenchmarkFastTemplateExecuteFuncString-4 3000000 549 ns/op 144 B/op 1 allocs/op BenchmarkFastTemplateExecuteString-4 3000000 572 ns/op 144 B/op 1 allocs/op BenchmarkFastTemplateExecuteTagFunc-4 2000000 743 ns/op 144 B/op 3 allocs/op ``` # 文档 请访问 http://godoc.org/github.com/valyala/fasttemplate 。 # 用法 ``` template := "http://{{host}}/?q={{query}}&foo={{bar}}{{bar}}" t := fasttemplate.New(template, "{{", "}}") s := t.ExecuteString(map[string]interface{}{ "host": "google.com", "query": url.QueryEscape("hello=world"), "bar": "foobar", }) fmt.Printf("%s", s) // Output: // http://google.com/?q=hello%3Dworld&foo=foobarfoobar ``` # 高级用法 ``` template := "Hello, [user]! You won [prize]!!! [foobar]" t, err := fasttemplate.NewTemplate(template, "[", "]") if err != nil { log.Fatalf("unexpected error when parsing template: %s", err) } s := t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) { switch tag { case "user": return w.Write([]byte("John")) case "prize": return w.Write([]byte("$100500")) default: return w.Write([]byte(fmt.Sprintf("[unknown tag %q]", tag))) } }) fmt.Printf("%s", s) // Output: // Hello, John! You won $100500!!! [unknown tag "foobar"] ```
标签:EVTX分析, Go, Ruby工具, 字符串处理, 开发工具库, 日志审计, 模板引擎