wireguard-dashboard/component/template.go
coward 941b8da804
All checks were successful
continuous-integration/drone/tag Build is passing
🐛修复模板渲染bug
2024-08-20 14:24:13 +08:00

93 lines
1.9 KiB
Go

package component
import (
"gitee.ltd/lxh/logger/log"
"html/template"
"os"
"strings"
)
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
}
tp, err = template.New("wg.conf").Funcs(t.FuncMap()).Parse(string(file))
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)
}
// 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,
}
}