initialize

package module
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 5, 2026 License: MIT Imports: 28 Imported by: 5

README

initialize

基于反射自动注入的config及dao(data access object)初始化,暴露一个全局变量,记录模块信息 initialize

example

go run _example/main.go -c _example/config/config.toml

feature

  • 默认支持local config,支持本地多配置文件
  • 支持环境区分(dev,test,prod,可自定义)
  • 支持环境变量
  • 支持命令行flag
  • 支持监听文件变更
  • 支持viper支持的所有格式("json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini")
  • 支持远程配置中心,支持nacos,apollo,etcd,http请求作为配置中心,可自定义扩展

quick start

配置模板
# dev | test | stage | prod |...
Env = "dev" # 将会选择与Env名字相同的环境配置
[dev]
ConfigTemplateDir = "." # 模板目录,将会生成配置模板

仅需以上最小配置,点击启动,即可生成配置模板 如果还是麻烦,试试直接用 ${your app}.exe --format ${配置格式} -e ${环境} -p ${模板路径} 启动吧

启动配置

启动配置作为根配置,不会监听更改,用于记录应用名称,区分环境,配置不同环境所需的本地配置及配置中心,后续配置均从本地配置及配置中心加载及自动更新

Name = "hoper"
# dev | test | stage | prod |...
Env = "dev" # 将会选择与Env名字相同的环境配置

[dev]
debug = true
SkipInjectDaos = ["Apollo","Etcd", "Es"]
ConfigTemplateDir = "." # 将会生成配置模板
# 上方是一个个初始配置,如果不知道如何进行接下来的配置,可以先启动生成配置模板
[dev.localConfig]
Paths = ["local.toml"]
ReloadInterval = "1s"

[dev.ConfigCenter]
Format = "toml"
Type = "nacos"

[dev.ConfigCenter.http]
Url = "http://localhost:6666/local.toml"
ReloadInterval = "1s"

[dev.ConfigCenter.nacos]
DataId = "pro"
Group = "DEFAULT_GROUP"

[[dev.ConfigCenter.nacos.ServerConfigs]]
Scheme = "http"
IpAddr = "nacos"
Port = 9000
GrpcPort = 10000

[dev.ConfigCenter.nacos.ClientConfig]
NamespaceId = "xxx"
username = "nacos"
password = "nacos"
LogLevel = "debug"

import(
  "github.com/hopeio/initialize"
)
type config struct {
	//自定义的配置
	Customize serverConfig
}
type serverConfig struct{
    TokenMaxAge time.Duration
}


// 注入配置前初始化
func (c *config) BeforeInject() {
    c.Customize.TokenMaxAge = time.Second * 60 * 60 * 24
}
// 注入配置后初始化
func (c *config) AfterInject() {
	c.Customize.TokenMaxAge = time.Second * 60 * 60 * 24 * c.Customize.TokenMaxAge
}

func main() {
	global:= initialize.NewGlobal[*config,*initialize.EmbeddedPresets]()
    //配置初始化应该在第一位
    defer global.Cleanup()
}
Dao注入
import(
    "github.com/hopeio/initialize/contrib/gormdb/sqlite"
    initredis "github.com/hopeio/initialize/contrib/redis"
)
// dao dao.
type dao struct {
	// GORMDB 数据库连接
	GORMDB   *sqlite.DB
	StdDB    *sql.DB
}
// 注入配置前初始化
func (c *dao) BeforeInject() {
}
// 注入配置后初始化
func (c *dao) AfterInjectConfig() {
}
// 注入dao后初始化
func (d *dao) AfterInject() {
	db := d.GORMDB
	db.Callback().Create().Remove("gorm:save_before_associations")
	db.Callback().Create().Remove("gorm:save_after_associations")
	db.Callback().Update().Remove("gorm:save_before_associations")
	db.Callback().Update().Remove("gorm:save_after_associations")

	d.StdDB, _ = db.DB()
}
func main() {
    global:= initialize.NewGlobal[*config,*dao]()
    defer global.Cleanup()
}

原生集成了redis,gormdb(mysql,postgressql,sqlite),kafka,pebbledb,apollo,badgerdb,etcd,elasticsearch,nsq,ristretto,viper等,并且非常简单的支持自定义扩展,不局限于Dao对象,任何对象都支持根据配置自动注入生成

注入时使用root config
// initWithRootConfig
import "github.com/hopeio/initialize"
func (c *conf) BeforeInjectWithRoot(root *initialize.RootConfig) {
}
func (c *dao) BeforeInjectWithRoot(root *initialize.RootConfig) {
}
// AfterInjectConfigWithRoot(*initialize.RootConfig)
// AfterInjectWithRoot(*initialize.RootConfig)

单配置文件

如果你的项目不需要分环境,那么不要env这个配置,不要 -e flag,直接在启动目录放一个config.xxx文件即可 或者可以手动指定-c ${配置文件}

生成模板

要为单配置文件生成模板--format ${配置格式} -p ${模板路径}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DaoFieldType = reflect.TypeOf((*DaoField)(nil)).Elem()
View Source
var EmbeddedPresetsType = reflect.TypeOf((*EmbeddedPresets)(nil)).Elem()

Functions

func Decode added in v0.13.5

func Decode(dst any, mapData map[string]any, opts ...DecoderConfigOption) error

Decode decodes a map[string]any into dst using mapstructure with the default decoder options.

func GetRegisteredConfigCenter added in v0.13.12

func GetRegisteredConfigCenter() map[string]ConfigCenter

GetRegisteredConfigCenter returns a snapshot copy of all currently registered ConfigCenter instances.

func NewGlobal added in v0.4.0

func NewGlobal[C Config, D Dao](configCenter ...ConfigCenter) *globalConfig[C, D]

NewGlobal creates a globalConfig by allocating zero-value instances of C and D via reflection, then runs the full initialization sequence. var Global = initialize.NewGlobal[C,D]()

func NewGlobalConfig added in v0.9.0

func NewGlobalConfig[C Config](configCenter ...ConfigCenter) *globalConfig[C, *EmbeddedPresets]

NewGlobalConfig is a shortcut for applications that only need a Config (no custom Dao).

func NewGlobalWith added in v0.4.0

func NewGlobalWith[C Config, D Dao](conf C, dao D, configCenter ...ConfigCenter) *globalConfig[C, D]

NewGlobalWith creates a globalConfig with the provided Config and Dao instances and immediately runs the full initialization sequence.

func RegisterConfigCenter added in v0.13.12

func RegisterConfigCenter(c ConfigCenter)

RegisterConfigCenter registers a ConfigCenter implementation by its type name (lowercase letters only). Duplicate registrations are silently ignored.

func RegisterUnSupportTemplateTypes added in v0.12.0

func RegisterUnSupportTemplateTypes(types ...string)

RegisterUnSupportTemplateTypes appends additional type name strings that should be excluded from config template generation (e.g. types that cannot be marshaled generically).

func Start

func Start[C Config, D Dao](conf C, dao D, configCenter ...ConfigCenter) func()

Start is a convenience wrapper around NewGlobalWith that returns only the Cleanup function.

Types

type BasicConfig added in v0.13.12

type BasicConfig struct {
	// 模块名
	Name string `flag:"name:name;usage:模块名;env:NAME"`
	// environment
	Env string `flag:"name:env;short:e;default:dev;usage:环境;env:ENV"`
}

BasicConfig

type Client added in v0.13.12

type Client interface {
	Get() ([]byte, error)
	Set(func([]byte)) error
	Listener(func([]byte)) error
}

type CloseFunc added in v0.13.12

type CloseFunc func() error

type Config

type Config interface {
	// contains filtered or unexported methods
}

Config is the interface that application configs must implement. BeforeInject sets default values before unmarshaling; AfterInject runs post-unmarshal initialization.

type ConfigCenter added in v0.13.12

type ConfigCenter interface {
	Config() any
	io.Closer
	Handle(ctx context.Context, merge func(io.Reader) error, onChange func(io.Reader) error) error
	Type() string
}

func GetConfigCenter added in v0.13.12

func GetConfigCenter(configType string) ConfigCenter

GetConfigCenter returns the registered ConfigCenter for the given type string, or nil if not found.

type ConfigCenterConfig added in v0.13.12

type ConfigCenterConfig struct {
	// 配置格式
	Format string `flag:"name:format;usage:配置格式"`
	// 配置类型
	Type string `flag:"name:conf_type;usage:配置类型"`
	// config字段顺序不能变,ConfigCenter 保持在最后
	ConfigCenter ConfigCenter
}

type ConfigType added in v0.13.12

type ConfigType string

type Dao

type Dao interface {
	// contains filtered or unexported methods
}

Dao is the interface that DAO structs must implement. AfterInjectConfig runs after config is unmarshaled; AfterInject runs after all DAO fields are initialized.

type DaoConfig added in v0.13.12

type DaoConfig[D any] interface {
	Build() (*D, CloseFunc, error)
}

type DaoField added in v0.13.12

type DaoField interface {
	Config() any
	Init() error
	io.Closer
}

type DaoG added in v0.13.12

type DaoG[C DaoConfig[D], D any] struct {
	Conf   C
	Client *D
	// contains filtered or unexported fields
}

func (*DaoG[C, D]) Close added in v0.13.12

func (d *DaoG[C, D]) Close() error

Close calls the cleanup function returned by Build, if any.

func (*DaoG[C, D]) Config added in v0.13.12

func (d *DaoG[C, D]) Config() any

Config returns the embedded Conf pointer as the configuration object for injection.

func (*DaoG[C, D]) Init added in v0.13.12

func (d *DaoG[C, D]) Init() error

Init calls Build on the configuration and stores the resulting client.

type DecoderConfigOption added in v0.13.5

type DecoderConfigOption func(*mapstructure.DecoderConfig)

type EmbeddedPresets

type EmbeddedPresets struct {
}

func (*EmbeddedPresets) AfterInject added in v0.0.33

func (u *EmbeddedPresets) AfterInject()

AfterInject is a no-op placeholder satisfying the Config/Dao interface.

func (*EmbeddedPresets) AfterInjectConfig added in v0.0.33

func (u *EmbeddedPresets) AfterInjectConfig()

AfterInjectConfig is a no-op placeholder satisfying the Dao interface.

func (*EmbeddedPresets) BeforeInject added in v0.0.33

func (u *EmbeddedPresets) BeforeInject()

BeforeInject is a no-op placeholder satisfying the Config/Dao interface.

type EnvConfig added in v0.13.12

type EnvConfig struct {
	Debug             bool   `flag:"name:debug;short:d;default:true;usage:是否测试;env:DEBUG"`
	ConfigTemplateDir string `flag:"name:conf_tmpl_dir;usage:是否生成配置模板;env:CONFIG_TEMPLATE_DIR"`
	// 代理, socks5://localhost:1080
	Proxy          string   `flag:"name:proxy;usage:代理;env:HTTP_PROXY" `
	SkipInjectDaos []string `flag:"name:skip_inject_daos;usage:跳过注入的dao"`
	LocalConfig    Local
	// config字段顺序不能变,ConfigCenter 保持在最后
	ConfigCenter ConfigCenterConfig
}

func (*EnvConfig) AfterInject added in v0.13.12

func (c *EnvConfig) AfterInject()

AfterInject sets up the HTTP proxy from the Proxy field and resolves all local config paths to absolute paths.

type Init added in v0.0.35

type Init interface {
	Init()
}

type Local added in v0.6.0

type Local struct {
	Watch bool
	Paths []string
	// contains filtered or unexported fields
}

func (*Local) Close added in v0.6.0

func (ld *Local) Close() error

Close stops the fsnotify watcher, if one is running.

func (*Local) Config added in v0.6.0

func (ld *Local) Config() any

Config returns the Local struct itself as its own configuration.

func (*Local) Handle added in v0.6.0

func (ld *Local) Handle(ctx context.Context, merge func(io.Reader) error, onChange func(io.Reader) error) (err error)

Load will unmarshal configurations to struct from files that you provide

func (*Local) Type added in v0.6.0

func (ld *Local) Type() string

Type returns the identifier string "local" for this config source.

type LogConfig added in v0.13.12

type LogConfig log.Config

全局变量,只一个实例,只提供config

func (*LogConfig) AfterInjectWithRoot added in v0.13.12

func (c *LogConfig) AfterInjectWithRoot(rootconfig *RootConfig)

AfterInjectWithRoot configures and replaces the default global logger using the root config's Name and Debug fields. It is a no-op if the config is still fully zero-valued.

type RootConfig added in v0.13.12

type RootConfig struct {
	Executable string `init:"-"` // autowired
	ExecDir    string `init:"-"` // autowired
	// 配置文件路径
	ConfPath string `flag:"name:config;short:c;usage:配置文件路径,默认./config.xxx或./config/config.xxx;env:CONFIG"`
	BasicConfig
	EnvConfig
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL