gitee.com/h79/goutils@v1.22.10/common/template/format.go (about) 1 package template 2 3 import ( 4 "gitee.com/h79/goutils/common/json" 5 "gitee.com/h79/goutils/common/logger" 6 "gitee.com/h79/goutils/common/result" 7 "io/fs" 8 "text/template" 9 ) 10 11 type Format struct { 12 engine *Engine 13 command template.FuncMap 14 items Items 15 } 16 17 type Option struct { 18 Data map[string]interface{} 19 } 20 21 type HandlerFunc func(source interface{}, opt *Option) error 22 23 type CommandFunc func(source interface{}, opt *Option, handler HandlerFunc) error 24 25 func DefFormat() *Format { 26 engine := DefEngine() 27 return NewFormat(engine) 28 } 29 30 func NewFormat(engine *Engine) *Format { 31 return &Format{ 32 engine: engine, 33 command: make(template.FuncMap), 34 } 35 } 36 37 func (ft *Format) Load(path string) error { 38 if err := json.Read(path, &ft.items); err != nil { 39 return err 40 } 41 logger.Debug("Template: conf= %+v", ft.items) 42 return nil 43 } 44 45 func (ft *Format) LoadTemplate(path string) { 46 ft.engine.LoadGlob(path) 47 } 48 49 func (ft *Format) LoadString(str string) { 50 ft.engine.LoadString(str) 51 } 52 53 func (ft *Format) LoadFS(f fs.FS, patterns ...string) { 54 ft.engine.LoadFS(f, patterns...) 55 } 56 57 func (ft *Format) AddCommand(funcName string, funcCall CommandFunc) { 58 ft.command[funcName] = funcCall 59 } 60 61 func (ft *Format) Format(format, appId, filter string, source interface{}, handler HandlerFunc) (*Data, error) { 62 63 reply, exists := ft.items.ItMap[appId] 64 if !exists { 65 return nil, result.Error(result.ErrNotFound, "Not found config") 66 } 67 68 var tpl Content 69 if format == "xml" { 70 tpl, exists = reply.Xml[filter] 71 } else if format == "json" { 72 tpl, exists = reply.Json[filter] 73 } else { 74 return nil, result.Error(result.ErrException, "Not support the format") 75 } 76 if !exists { 77 return nil, result.Error(result.ErrNotFound, "Not found the filter content") 78 } 79 var cmd CommandFunc = nil 80 if f, ok := ft.command[tpl.Func]; ok { 81 cmd = f.(CommandFunc) 82 } 83 return ft.FormatWith(cmd, tpl.Name, source, handler) 84 } 85 86 func (ft *Format) FormatWith(cmdFn CommandFunc, tplName string, source interface{}, handler HandlerFunc) (*Data, error) { 87 opt := Option{ 88 Data: map[string]interface{}{}, 89 } 90 if err := cmdFn(source, &opt, func(source interface{}, opt *Option) error { 91 if handler != nil { 92 return handler(source, opt) 93 } 94 return nil 95 }); err != nil { 96 return nil, err 97 } 98 return ft.engine.OUTPUT(tplName, opt.Data) 99 }