go的template示例3
改进:保存配置定义的顺序。
实现代码:
package main
import (
"os"
"strings"
"text/template"
"github.com/stoewer/go-strcase"
)
type ConfigItem struct {
Key string
Value map[string]string
}
func main() {
// 定义模板函数
funcs := template.FuncMap{
"title": strings.Title,
"lower": strcase.SnakeCase,
"sub": func(a, b int) int {
return a - b
},
"add": func(a, b int) int {
return a + b
},
"split": func(s, sep string) []string {
return strings.Split(s, sep)
},
}
Configs := []ConfigItem{
{Key: "DbConfig", Value: map[string]string{"Type": "db.DbConfig"}},
{Key: "KafkaConsumerConfig", Value: map[string]string{"Type": "kafka.KafkaConsumerConfig"}},
{Key: "Db1", Value: map[string]string{"Type": "db.DbConfig"}},
{Key: "DbAa", Value: map[string]string{"Type": "db.DbConfig"}},
{Key: "Redis", Value: map[string]string{"Type": "RedisConfig"}},
}
tmpl, err := template.New("a.go.tpl").Funcs(funcs).ParseFiles("./a.go.tpl")
if err != nil {
panic(err)
}
// 执行模板
err = tmpl.Execute(os.Stdout, map[string]interface{}{
"Configs": Configs,
})
if err != nil {
panic(err)
}
}
模板文件:
package core
{{- if gt (len .Configs) 0 }}
import (
"db"
"github.com/kafka"
"RedisConfig"
)
{{- end }}
type Config struct {
{{- $len := len .Configs -}}
{{- $i := 0 -}}
{{- range $config := .Configs }}
{{- $parts := split $config.Key "." -}}
{{- if ge (len $parts) 2 }}
{{title (index $parts 1)}} *{{index $config.Value "Type"}} `yaml:"{{lower (index $parts 1)}}"`
{{- else }}
{{title $config.Key}} *{{index $config.Value "Type"}} `yaml:"{{lower $config.Key}}"`
{{- end }}
{{- if lt $i (sub $len 1)}},{{end}}
{{- $i = add $i 1 -}}
{{- end }}
}
执行输出:
package core
import (
"db"
"github.com/kafka"
"RedisConfig"
)
type Config struct {
DbConfig *db.DbConfig `yaml:"db_config"`,
KafkaConsumerConfig *kafka.KafkaConsumerConfig `yaml:"kafka_consumer_config"`,
Db1 *db.DbConfig `yaml:"db1"`,
DbAa *db.DbConfig `yaml:"db_aa"`,
Redis *RedisConfig `yaml:"redis"`
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义