feat: port engine from lib/ksrv

master
Evan Chen 2021-11-24 12:43:32 +08:00
parent cd95cf5454
commit f03173b8a9
1 changed files with 102 additions and 0 deletions

102
netutil/engine.go Normal file
View File

@ -0,0 +1,102 @@
package netutil
import (
"bytes"
"html/template"
"io"
"io/fs"
"path/filepath"
)
type Engine struct {
name string
Template *template.Template
}
func NewEngine(name string) *Engine {
Ename := "E" + name
if Ename == "E" {
Ename = "Engine"
}
return &Engine{Ename, template.New(name)}
}
func (e *Engine) Funcs(funcMap template.FuncMap) *Engine {
e.Template = e.Template.Funcs(funcMap)
return e
}
func (e *Engine) Parse(text string) (*Engine, error) {
tmp, err := e.Template.Parse(text)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) ParseFS(fs fs.FS, patterns ...string) (*Engine, error) {
tmp, err := e.Template.ParseFS(fs, patterns...)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) ParseFiles(filenames ...string) (*Engine, error) {
tmp, err := e.Template.ParseFiles(filenames...)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) ParseGlob(pattern string) (*Engine, error) {
tmp, err := e.Template.ParseGlob(pattern)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) OverrideGlob(pattern string) (*Engine, error) {
matches, _ := filepath.Glob(pattern)
if len(matches) <= 0 {
// surpass error if no tmpl found
return e, nil
}
tmp, err := e.Template.ParseGlob(pattern)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func Must(e *Engine, err error) *Engine {
if err != nil {
panic(err)
}
return e
}
func (e *Engine) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
buf := &bytes.Buffer{}
err := e.Template.ExecuteTemplate(buf, name, data)
if err != nil {
return err
}
_, err = wr.Write(buf.Bytes())
return err
}
func (e *Engine) Execute(wr io.Writer, data interface{}) error {
buf := &bytes.Buffer{}
err := e.Template.Execute(buf, data)
if err != nil {
return err
}
_, err = wr.Write(buf.Bytes())
return err
}