Documentation
¶
Overview ¶
Package boot provides application bootstrapping: config loading, logger, database connections, Redis, and graceful lifecycle management.
Index ¶
- func InitLogger(mode, serviceName string)
- func LoadConfig(path string, cfg any) error
- func LoadRemoteConfig(reg RegistryConfig, serviceName string, cfg any) error
- func MergeRemoteConfig(reg RegistryConfig, serviceName string, base *Config) error
- func OpenAllDBs(cfgs map[string]DatabaseConfig, mode string) (map[string]*gorm.DB, error)
- func OpenDB(cfg DatabaseConfig, mode string) (*gorm.DB, error)
- func OpenRedis(cfg RedisConfig) (*redis.Client, error)
- func WatchRemoteConfig(ctx context.Context, reg RegistryConfig, serviceName string, ...) error
- type AccessLimitConfig
- type App
- type CORSConfig
- type Config
- type ConfigChangeFunc
- type DatabaseConfig
- type GRPCConfig
- type JWTConfig
- type LogConfig
- type NotifyConfig
- type RedisConfig
- type RegistryConfig
- type ServerConfig
- type SetupFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func InitLogger ¶
func InitLogger(mode, serviceName string)
InitLogger initializes the global logger (console only). Deprecated: use log.Init() directly. Kept for backward compatibility.
func LoadConfig ¶
LoadConfig reads a YAML config file into cfg. Environment variables DATABASE_DSN and REDIS_ADDR override file values.
func LoadRemoteConfig ¶ added in v0.7.0
func LoadRemoteConfig(reg RegistryConfig, serviceName string, cfg any) error
LoadRemoteConfig reads a config value from etcd or consul KV and unmarshals it into cfg.
func MergeRemoteConfig ¶ added in v0.7.0
func MergeRemoteConfig(reg RegistryConfig, serviceName string, base *Config) error
MergeRemoteConfig loads config from registry's KV backend and deep-merges it into base. Only keys present in the remote config are overwritten.
Merge order: local → service shared → node-specific.
func OpenAllDBs ¶
OpenAllDBs opens all databases defined in config. On failure, already-opened connections are closed before returning.
func OpenDB ¶
func OpenDB(cfg DatabaseConfig, mode string) (*gorm.DB, error)
OpenDB creates a GORM database connection with production-ready pool settings.
func OpenRedis ¶
func OpenRedis(cfg RedisConfig) (*redis.Client, error)
OpenRedis creates a Redis client. Returns nil if Addr is empty.
func WatchRemoteConfig ¶ added in v0.7.0
func WatchRemoteConfig(ctx context.Context, reg RegistryConfig, serviceName string, onChange func([]byte)) error
WatchRemoteConfig watches the service config key for changes and calls onChange with new raw bytes. Blocks until ctx is cancelled.
Types ¶
type AccessLimitConfig ¶ added in v0.3.0
type AccessLimitConfig struct {
Enable bool `mapstructure:"enable"`
Total int `mapstructure:"total"` // max requests per window (default 300)
Duration int `mapstructure:"duration"` // window in seconds (default 5)
}
AccessLimitConfig describes rate limiting.
type App ¶
type App struct {
Config *Config
Gin *gin.Engine
DBs map[string]*gorm.DB
Redis *redis.Client
GRPC *grpc.Server
Registry registry.Registry
// contains filtered or unexported fields
}
App is the central service instance holding all shared resources.
func (*App) GetConfig ¶ added in v0.9.0
GetConfig returns the current config (thread-safe for use during runtime). During setup (before Run), accessing a.Config directly is fine.
func (*App) OnClose ¶
func (a *App) OnClose(fn func())
OnClose registers a callback invoked during graceful shutdown.
func (*App) OnConfigChange ¶ added in v0.8.0
func (a *App) OnConfigChange(fn ConfigChangeFunc)
OnConfigChange registers a callback invoked when remote config changes. The callback receives the new Config. Return an error to reject the update (Config will not be replaced). Multiple callbacks run in order.
type CORSConfig ¶ added in v0.3.0
type CORSConfig struct {
Enable bool `mapstructure:"enable"`
Mode string `mapstructure:"mode"` // "allow-all" or "whitelist"
Whitelist []string `mapstructure:"whitelist"` // allowed origins
}
CORSConfig describes CORS settings.
type Config ¶
type Config struct {
Server ServerConfig `mapstructure:"server"`
Log LogConfig `mapstructure:"log"`
Database map[string]DatabaseConfig `mapstructure:"database"`
Redis RedisConfig `mapstructure:"redis"`
GRPC GRPCConfig `mapstructure:"grpc"`
Registry RegistryConfig `mapstructure:"registry"`
JWT JWTConfig `mapstructure:"jwt"`
CORS CORSConfig `mapstructure:"cors"`
AccessLimit AccessLimitConfig `mapstructure:"accessLimit"`
Notify NotifyConfig `mapstructure:"notify"`
}
Config is the base service configuration. Embed it in your own config struct to add service-specific fields.
func LoadBaseConfig ¶
LoadBaseConfig is a convenience wrapper that loads into a *Config.
type ConfigChangeFunc ¶ added in v0.8.0
ConfigChangeFunc is called when remote config changes. It receives the updated Config; return an error to reject the update.
type DatabaseConfig ¶
type DatabaseConfig struct {
DSN string `mapstructure:"dsn"`
MaxIdle int `mapstructure:"maxIdle"` // max idle connections (default 10)
MaxOpen int `mapstructure:"maxOpen"` // max open connections (default 50)
MaxLifetime int `mapstructure:"maxLifetime"` // max connection lifetime in seconds (default 3600)
MaxIdleTime int `mapstructure:"maxIdleTime"` // max idle time in seconds (default 300)
SlowThreshold int `mapstructure:"slowThreshold"` // slow query threshold in ms (default 200)
PingOnOpen bool `mapstructure:"pingOnOpen"` // ping DB on open to verify connectivity (default true)
}
DatabaseConfig describes a single database connection.
type GRPCConfig ¶
type GRPCConfig struct {
Enable bool `mapstructure:"enable"`
Addr string `mapstructure:"addr"` // e.g. ":7889"
}
GRPCConfig describes an optional gRPC listener.
type JWTConfig ¶ added in v0.3.0
type JWTConfig struct {
Secret string `mapstructure:"secret"`
Expires int `mapstructure:"expires"` // minutes
Refresh int `mapstructure:"refresh"` // minutes, auto-refresh window
Issuer string `mapstructure:"issuer"`
Subject string `mapstructure:"subject"`
}
JWTConfig describes JWT authentication settings.
type LogConfig ¶ added in v0.6.0
type LogConfig struct {
Output string `mapstructure:"output"` // "console" (default), "file", "both"
File log.FileConfig `mapstructure:"file"`
}
LogConfig describes log output targets.
output: "console" (default), "file", or "both"
type NotifyConfig ¶ added in v0.3.0
type NotifyConfig struct {
WsURL string `mapstructure:"wsUrl"` // mf-ws internal API base URL
}
NotifyConfig describes the WebSocket notification target.
type RedisConfig ¶
type RedisConfig struct {
Addr string `mapstructure:"addr"`
Username string `mapstructure:"username"` // Redis 6+ ACL username (optional)
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
}
RedisConfig describes a Redis connection. Leave Addr empty to disable.
type RegistryConfig ¶
type RegistryConfig struct {
Enable bool `mapstructure:"enable"`
Type string `mapstructure:"type"` // "etcd" (default) or "consul"
Endpoints []string `mapstructure:"endpoints"` // etcd endpoints, e.g. ["127.0.0.1:2379"]
Address string `mapstructure:"address"` // consul address, e.g. "127.0.0.1:8500"
Token string `mapstructure:"token"` // consul ACL token (optional)
Prefix string `mapstructure:"prefix"` // service discovery prefix, default "/mofang/services/"
TTL int `mapstructure:"ttl"` // lease/check TTL in seconds, default 30
ConfigKey string `mapstructure:"configKey"` // remote config key prefix, e.g. "/config/" → auto appends server.name
ConfigNode string `mapstructure:"configNode"` // node ID for per-instance override (optional, or env REMOTE_NODE)
ConfigFormat string `mapstructure:"configFormat"` // "yaml" (default) or "json"
}
RegistryConfig describes the service registry (etcd or consul). It also drives optional remote config loading from the same backend.
type ServerConfig ¶
type ServerConfig struct {
Name string `mapstructure:"name"`
Addr string `mapstructure:"addr"` // e.g. ":7801"
Mode string `mapstructure:"mode"` // "debug" or "release"
}
ServerConfig describes the HTTP server.