2024-07-05 14:41:35 +08:00
|
|
|
package component
|
|
|
|
|
|
|
|
import (
|
|
|
|
"gitee.ltd/lxh/logger/log"
|
|
|
|
"html/template"
|
|
|
|
"os"
|
2024-08-20 14:24:13 +08:00
|
|
|
"strings"
|
2024-07-05 14:41:35 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type TemplateComponent struct{}
|
|
|
|
|
|
|
|
func Template() TemplateComponent {
|
|
|
|
return TemplateComponent{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Execute
|
|
|
|
// @description: 渲染数据模板并生成对应文件
|
|
|
|
// @receiver t
|
|
|
|
// @param templateFilePath
|
|
|
|
// @param outFilePath
|
|
|
|
// @param data
|
|
|
|
// @return err
|
|
|
|
func (t TemplateComponent) Execute(templateFilePath, outFilePath string, data any) (err error) {
|
|
|
|
parseTemplate, err := t.ParseTemplate(templateFilePath)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("解析模板信息失败:%v", err.Error())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = t.Render(parseTemplate, data, outFilePath)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("渲染模板失败: %v", err.Error())
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ParseTemplate
|
|
|
|
// @description: 解析模板
|
|
|
|
// @receiver t
|
|
|
|
// @param filepath
|
|
|
|
// @return t
|
|
|
|
// @return err
|
|
|
|
func (t TemplateComponent) ParseTemplate(filepath string) (tp *template.Template, err error) {
|
|
|
|
file, err := os.ReadFile(filepath)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-08-20 14:24:13 +08:00
|
|
|
tp, err = template.New("wg.conf").Funcs(t.FuncMap()).Parse(string(file))
|
2024-07-05 14:41:35 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Render
|
|
|
|
// @description: 渲染模板
|
|
|
|
// @receiver t
|
|
|
|
// @param tp
|
|
|
|
// @param data
|
|
|
|
// @param filepath
|
|
|
|
// @return err
|
|
|
|
func (t TemplateComponent) Render(tp *template.Template, data any, filepath string) (err error) {
|
|
|
|
wg0Conf, err := os.Create(filepath)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("创建文件[%s]失败: %v", filepath, err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
if err = wg0Conf.Close(); err != nil {
|
|
|
|
log.Errorf("关闭文件[%s]失败: %v", filepath, err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return tp.Execute(wg0Conf, data)
|
|
|
|
}
|
2024-08-20 14:24:13 +08:00
|
|
|
|
|
|
|
// FuncMap
|
|
|
|
// @description: 模板内的操作方法
|
|
|
|
// @receiver t
|
|
|
|
// @return template.FuncMap
|
|
|
|
// @return error
|
|
|
|
func (t TemplateComponent) FuncMap() template.FuncMap {
|
|
|
|
sliceToString := func(str []string) string {
|
|
|
|
return strings.Join(str, ",")
|
|
|
|
}
|
|
|
|
|
|
|
|
return template.FuncMap{
|
|
|
|
"sliceToStr": sliceToString,
|
|
|
|
}
|
|
|
|
}
|