岚天逸见

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"`
}

posted on   岚天逸见  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义

导航

统计信息

点击右上角即可分享
微信分享提示