1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
format.go 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-06-19 01:50 . 修改命名
package template
import (
"gitee.com/h79/goutils/common/json"
"gitee.com/h79/goutils/common/logger"
"gitee.com/h79/goutils/common/result"
"text/template"
)
type Format struct {
engine *Engine
command template.FuncMap
items Items
}
type Handler func(source interface{}, d D) error
type Command func(source interface{}, d D, handler Handler) 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) AddCommand(funcName string, funcCall Command) {
ft.command[funcName] = funcCall
}
func (ft *Format) Format(format, appId, filter string, source interface{}, handler Handler) (*Data, error) {
reply, exists := ft.items.ItMap[appId]
if !exists {
return nil, result.Error(result.ErrNotFound, "Not found config")
}
var tmpl Content
if format == "xml" {
tmpl, exists = reply.Xml[filter]
} else if format == "json" {
tmpl, 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")
}
d := D{}
if f, ok := ft.command[tmpl.Func]; ok {
if err := f.(Command)(source, d, func(source interface{}, d D) error {
if handler != nil {
return handler(source, d)
}
return nil
}); err != nil {
}
}
return ft.engine.OUTPUT(tmpl.Name, d)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.1.24

搜索帮助