go的template示例2
改进:配置类型模板化
实现代码:
package main
import (
"os"
"strings"
"text/template"
"github.com/stoewer/go-strcase"
)
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 := map[string]interface{}{
"DbConfig": map[string]string{
"Type": "db.DbConfig",
},
"KafkaConsumerConfig": map[string]string{
"Type": "kafka.KafkaConsumerConfig",
},
"Db1": map[string]string{
"Type": "db.DbConfig",
},
"DbAa": map[string]string{
"Type": "db.DbConfig",
},
"Redis": 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)
}
}
模板文件:
# cat a.go.tpl
package core
{{- if gt (len .Configs) 0 }}
import (
"github.com/kafka"
)
{{- end }}
type Config struct {
{{- $len := len .Configs -}}
{{- $i := 0 -}}
{{- range $key, $value := .Configs}}
{{- $parts := split $key "." -}}
{{- if ge (len $parts) 2 }}
{{title (index $parts 1)}} *{{index $value "Type"}} `yaml:"{{lower (index $parts 1)}}"`
{{- else }}
{{title $key}} *{{index $value "Type"}} `yaml:"{{lower $key}}"`
{{- end }}
{{- if lt $i (sub $len 1)}},{{end}}
{{- $i = add $i 1 -}}
{{- end }}
}
执行输出:
package core
import (
"github.com/kafka"
)
type Config struct {
Db1 *db.DbConfig `yaml:"db1"`,
DbAa *db.DbConfig `yaml:"db_aa"`,
DbConfig *db.DbConfig `yaml:"db_config"`,
KafkaConsumerConfig *kafka.KafkaConsumerConfig `yaml:"kafka_consumer_config"`,
Redis *RedisConfig `yaml:"redis"`
}
原文地址:https://blog.csdn.net/Aquester/article/details/143492438
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!