1 Star 0 Fork 0

h79 / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
format.go 2.23 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-02-19 13:58 . log
package template
import (
"gitee.com/h79/goutils/common/json"
"gitee.com/h79/goutils/common/logger"
"gitee.com/h79/goutils/common/result"
"io/fs"
"text/template"
)
type Format struct {
engine *Engine
command template.FuncMap
items Items
}
type Option struct {
Data map[string]interface{}
}
type HandlerFunc func(source interface{}, opt *Option) error
type CommandFunc func(source interface{}, opt *Option, handler HandlerFunc) error
func DefFormat() *Format {
engine := DefEngine()
return NewFormat(engine)
}
func NewFormat(engine *Engine) *Format {
return &Format{
engine: engine,
command: make(template.FuncMap),
}
}
func (ft *Format) Load(path string) error {
if err := json.Read(path, &ft.items); err != nil {
return err
}
logger.Debug("Template: conf= %+v", ft.items)
return nil
}
func (ft *Format) LoadTemplate(path string) {
ft.engine.LoadGlob(path)
}
func (ft *Format) LoadString(str string) {
ft.engine.LoadString(str)
}
func (ft *Format) LoadFS(f fs.FS, patterns ...string) {
ft.engine.LoadFS(f, patterns...)
}
func (ft *Format) AddCommand(funcName string, funcCall CommandFunc) {
ft.command[funcName] = funcCall
}
func (ft *Format) Format(format, appId, filter string, source interface{}, handler HandlerFunc) (*Data, error) {
reply, exists := ft.items.ItMap[appId]
if !exists {
return nil, result.Error(result.ErrNotFound, "Not found config")
}
var tpl Content
if format == "xml" {
tpl, exists = reply.Xml[filter]
} else if format == "json" {
tpl, exists = reply.Json[filter]
} else {
return nil, result.Error(result.ErrException, "Not support the format")
}
if !exists {
return nil, result.Error(result.ErrNotFound, "Not found the filter content")
}
var cmd CommandFunc = nil
if f, ok := ft.command[tpl.Func]; ok {
cmd = f.(CommandFunc)
}
return ft.FormatWith(cmd, tpl.Name, source, handler)
}
func (ft *Format) FormatWith(cmdFn CommandFunc, tplName string, source interface{}, handler HandlerFunc) (*Data, error) {
opt := Option{
Data: map[string]interface{}{},
}
if err := cmdFn(source, &opt, func(source interface{}, opt *Option) error {
if handler != nil {
return handler(source, opt)
}
return nil
}); err != nil {
return nil, err
}
return ft.engine.OUTPUT(tplName, opt.Data)
}
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.57

搜索帮助

53164aa7 5694891 3bd8fe86 5694891