岚天逸见

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 2024-11-04 19:49  岚天逸见  阅读(4)  评论(0编辑  收藏  举报

导航