Documentation
¶
Overview ¶
Package config provides centralized configuration management for ncore applications using Viper with support for multiple formats, environment variables, and hot-reloading.
This package manages application configuration including:
- Server settings (HTTP, gRPC)
- Database connections (PostgreSQL, MySQL, MongoDB, Redis)
- Message queues (Kafka, RabbitMQ)
- Search engines (Elasticsearch, OpenSearch, Meilisearch)
- Storage (Object storage, filesystem)
- Security (JWT, encryption)
- Observability (logging, tracing, metrics, Sentry)
- Email services (SMTP, SendGrid, Mailgun, etc.)
Configuration Loading ¶
Load configuration from file:
cfg, err := config.Load()
if err != nil {
log.Fatal(err)
}
Load with custom path:
cfg, err := config.LoadWithPath("./config/app.yaml")
Configuration Format ¶
Supports YAML, JSON, and TOML formats. Example YAML:
server:
host: 0.0.0.0
port: 8080
mode: production
database:
master:
driver: postgres
host: localhost
port: 5432
database: myapp
jwt:
secret: your-secret-key
expire: 24h
Environment Variables ¶
Override config values with environment variables using underscores:
export SERVER_PORT=9000 export DATABASE_MASTER_HOST=db.example.com export JWT_SECRET=production-secret
Environment variables take precedence over file configuration.
Hot Reloading ¶
Watch configuration file for changes:
config.WatchConfig(func(cfg *config.Config) {
log.Println("Configuration reloaded")
// React to configuration changes
})
Default Values ¶
The package provides sensible defaults for all settings:
- Server: port 8080, debug mode
- Database: localhost connections
- JWT: 24h expiration
- Connection pools: optimized sizes
- Timeouts: reasonable defaults
All helper functions (getDurationOrDefault, getIntOrDefault, etc.) automatically fall back to defaults when values are not specified.
Provider Sets ¶
The package exports Wire provider sets for dependency injection:
ProviderSet // Provides complete Config
Use with Wire for automatic configuration wiring in applications.
Index ¶
- Constants
- Variables
- func BindConfigToContext(ctx context.Context) context.Context
- func Reload() error
- func Watch(callback func(*Config))
- type AliyunConfig
- type Auth
- type Casbin
- type Config
- type Consul
- type DBNode
- type Data
- type Email
- type Extension
- type ExtensionMetrics
- type ExtensionMetricsStorage
- type ExtensionPerformance
- type ExtensionSecurity
- type Frontend
- type GRPC
- type JWT
- type LogDesensitization
- type Logger
- type LoggerElasticsearch
- type LoggerMeilisearch
- type LoggerOpenSearch
- type MailgunConfig
- type NetEaseConfig
- type OAuth
- type OAuthProvider
- type SMTPConfig
- type SendGridConfig
- type Sentry
- type Storage
- type TencentCloudConfig
- type Tracing
Constants ¶
const ExtensionBuiltInMode = "c2hlbgo"
ExtensionBuiltInMode represents the build tag value for built-in extension mode.
Variables ¶
var ProviderSet = wire.NewSet( GetConfig, ProvideLoggerConfig, ProvideDataConfig, ProvideExtensionConfig, ProvideAuthConfig, ProvideStorageConfig, ProvideEmailConfig, ProvideOAuthConfig, ProvideTracingConfig, ProvideSentryConfig, )
ProviderSet is the wire provider set for the config package. It provides the main *Config and extracts sub-configurations for other modules to use.
Usage:
wire.Build(
config.ProviderSet,
// ... other providers
)
Available configurations:
- *Config: Main configuration
- *Logger: Logger configuration
- *Data: Data layer configuration
- *Extension: Extension system configuration
- *Auth: Authentication configuration
- *Storage: Storage configuration
- *Email: Email configuration
- *OAuth: OAuth configuration
- *Tracing: OpenTelemetry tracing configuration
- *Sentry: Sentry error tracking configuration
Functions ¶
func BindConfigToContext ¶
BindConfigToContext binds the configuration to the context.
Types ¶
type AliyunConfig ¶ added in v0.2.5
type AliyunConfig struct {
ID string `json:"id" yaml:"id"`
Secret string `json:"secret" yaml:"secret"`
Account string `json:"account" yaml:"account"`
}
AliyunConfig contains Aliyun DirectMail credentials and sender settings.
type Auth ¶
type Auth struct {
JWT *JWT `json:"jwt" yaml:"jwt"`
Casbin *Casbin `json:"casbin" yaml:"casbin"`
Whitelist []string `json:"whitelist" yaml:"whitelist"`
MaxSessions int `json:"max_sessions" yaml:"max_sessions"`
SessionCleanupInterval int `json:"session_cleanup_interval" yaml:"session_cleanup_interval"`
}
Auth auth config struct
func ProvideAuthConfig ¶ added in v0.2.0
ProvideAuthConfig provides the authentication configuration.
type Config ¶
type Config struct {
AppName string `yaml:"app_name" json:"app_name"`
Environment string `yaml:"environment" json:"environment"`
Protocol string `yaml:"protocol" json:"protocol"`
Domain string `yaml:"domain" json:"domain"`
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
GRPC *GRPC `yaml:"grpc" json:"grpc"`
Consul *Consul `yaml:"consul" json:"consul"`
Tracing *Tracing `yaml:"tracing" json:"tracing"`
Sentry *Sentry `yaml:"sentry" json:"sentry"`
Extension *Extension `yaml:"extension" json:"extension"`
Frontend *Frontend `yaml:"frontend" json:"frontend"`
Logger *Logger `yaml:"logger" json:"logger"`
Data *Data `yaml:"data" json:"data"`
Auth *Auth `yaml:"auth" json:"auth"`
Storage *Storage `yaml:"storage" json:"storage"`
OAuth *OAuth `yaml:"oauth" json:"oauth"`
Email *Email `yaml:"email" json:"email"`
Viper *viper.Viper `yaml:"-" json:"-"`
}
Config represents the configuration implementation.
func GetConfig ¶
GetConfig returns the configuration. It does not handle errors internally; instead, it returns the error for the caller to handle.
func LoadConfig ¶
LoadConfig loads the configuration from the file.
type Consul ¶
type Consul struct {
Address string `yaml:"address" json:"address"`
Scheme string `yaml:"scheme" json:"scheme"`
Discovery struct {
DefaultTags []string `yaml:"default_tags" json:"default_tags"`
DefaultMeta map[string]string `yaml:"default_meta" json:"default_meta"`
HealthCheck bool `yaml:"health_check" json:"health_check"`
CheckInterval string `yaml:"check_interval" json:"check_interval"`
Timeout string `yaml:"timeout" json:"timeout"`
} `yaml:"discovery" json:"discovery"`
}
Consul config struct
type Data ¶
Data represents the data configuration
func ProvideDataConfig ¶ added in v0.2.0
ProvideDataConfig provides the data layer configuration.
type Email ¶
type Email struct {
Provider string `json:"provider" yaml:"provider"`
Mailgun *MailgunConfig `json:"mailgun" yaml:"mailgun"`
Aliyun *AliyunConfig `json:"aliyun" yaml:"aliyun"`
NetEase *NetEaseConfig `json:"netease" yaml:"netease"`
SendGrid *SendGridConfig `json:"sendgrid" yaml:"sendgrid"`
SMTP *SMTPConfig `json:"smtp" yaml:"smtp"`
TencentCloud *TencentCloudConfig `json:"tencent_cloud" yaml:"tencent_cloud"`
}
Email contains email provider infrastructure settings.
func ProvideEmailConfig ¶ added in v0.2.0
ProvideEmailConfig provides the email configuration.
type Extension ¶
type Extension struct {
Mode string `json:"mode" yaml:"mode"`
Path string `json:"path" yaml:"path"`
Includes []string `json:"includes" yaml:"includes"`
Excludes []string `json:"excludes" yaml:"excludes"`
HotReload bool `json:"hot_reload" yaml:"hot_reload"`
MaxPlugins int `json:"max_plugins" yaml:"max_plugins"`
PluginConfig map[string]any `json:"plugin_config" yaml:"plugin_config"`
Security *ExtensionSecurity `json:"security" yaml:"security"`
Performance *ExtensionPerformance `json:"performance" yaml:"performance"`
Metrics *ExtensionMetrics `json:"metrics" yaml:"metrics"`
}
Extension contains extension system infrastructure settings.
func GetExtensionConfig ¶ added in v0.2.5
GetExtensionConfig returns extension configuration and panics on invalid values.
func GetExtensionConfigE ¶ added in v0.2.5
GetExtensionConfigE returns extension configuration and validation errors.
func ProvideExtensionConfig ¶ added in v0.2.0
ProvideExtensionConfig provides the extension system configuration.
func (*Extension) IsBuiltInMode ¶ added in v0.2.5
IsBuiltInMode reports whether built-in extension loading is enabled.
type ExtensionMetrics ¶ added in v0.2.5
type ExtensionMetrics struct {
Enabled bool `json:"enabled" yaml:"enabled"`
FlushInterval string `json:"flush_interval" yaml:"flush_interval"`
BatchSize int `json:"batch_size" yaml:"batch_size"`
Retention string `json:"retention" yaml:"retention"`
Storage *ExtensionMetricsStorage `json:"storage" yaml:"storage"`
}
ExtensionMetrics contains extension metrics collection settings.
func (*ExtensionMetrics) GetRetentionDuration ¶ added in v0.2.5
func (m *ExtensionMetrics) GetRetentionDuration() (time.Duration, error)
GetRetentionDuration returns the configured metrics retention duration.
func (*ExtensionMetrics) Validate ¶ added in v0.2.5
func (m *ExtensionMetrics) Validate() error
Validate validates extension metrics settings.
type ExtensionMetricsStorage ¶ added in v0.2.5
type ExtensionMetricsStorage struct {
Type string `json:"type" yaml:"type"`
KeyPrefix string `json:"key_prefix" yaml:"key_prefix"`
Options map[string]string `json:"options" yaml:"options"`
}
ExtensionMetricsStorage contains extension metrics persistence settings.
type ExtensionPerformance ¶ added in v0.2.5
type ExtensionPerformance struct {
MaxMemoryMB int `json:"max_memory_mb" yaml:"max_memory_mb"`
MaxCPUPercent int `json:"max_cpu_percent" yaml:"max_cpu_percent"`
GarbageCollectInterval string `json:"gc_interval" yaml:"gc_interval"`
MaxConcurrentLoads int `json:"max_concurrent_loads" yaml:"max_concurrent_loads"`
}
ExtensionPerformance contains extension runtime limits.
type ExtensionSecurity ¶ added in v0.2.5
type ExtensionSecurity struct {
EnableSandbox bool `json:"enable_sandbox" yaml:"enable_sandbox"`
AllowedPaths []string `json:"allowed_paths" yaml:"allowed_paths"`
BlockedExtensions []string `json:"blocked_extensions" yaml:"blocked_extensions"`
TrustedSources []string `json:"trusted_sources" yaml:"trusted_sources"`
RequireSignature bool `json:"require_signature" yaml:"require_signature"`
AllowUnsafe bool `json:"allow_unsafe" yaml:"allow_unsafe"`
}
ExtensionSecurity contains extension sandbox and trust settings.
type Frontend ¶
type Frontend struct {
SignInURL string `json:"sign_in_url" yaml:"sign_in_url"`
SignUpURL string `json:"sign_up_url" yaml:"sign_up_url"`
}
Frontend frontend config struct
type GRPC ¶
type GRPC struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
// TLS Configuration
TLSEnabled bool `yaml:"tls_enabled" json:"tls_enabled"`
CertFile string `yaml:"cert_file" json:"cert_file"`
KeyFile string `yaml:"key_file" json:"key_file"`
CAFile string `yaml:"ca_file" json:"ca_file"` // For mTLS
// Connection Configuration
MaxConnIdle time.Duration `yaml:"max_conn_idle" json:"max_conn_idle"`
MaxConnAge time.Duration `yaml:"max_conn_age" json:"max_conn_age"`
KeepaliveTime time.Duration `yaml:"keepalive_time" json:"keepalive_time"`
KeepaliveTimeout time.Duration `yaml:"keepalive_timeout" json:"keepalive_timeout"`
// Performance Configuration
MaxConcurrentStreams uint32 `yaml:"max_concurrent_streams" json:"max_concurrent_streams"`
MaxRecvMsgSize int `yaml:"max_recv_msg_size" json:"max_recv_msg_size"` // bytes
MaxSendMsgSize int `yaml:"max_send_msg_size" json:"max_send_msg_size"` // bytes
}
type LogDesensitization ¶ added in v0.2.5
type LogDesensitization struct {
Enabled bool `json:"enabled" yaml:"enabled"`
SensitiveFields []string `json:"sensitive_fields" yaml:"sensitive_fields"`
CustomPatterns []string `json:"custom_patterns" yaml:"custom_patterns"`
PreservePrefix int `json:"preserve_prefix" yaml:"preserve_prefix"`
PreserveSuffix int `json:"preserve_suffix" yaml:"preserve_suffix"`
MaskChar string `json:"mask_char" yaml:"mask_char"`
UseFixedLength bool `json:"use_fixed_length" yaml:"use_fixed_length"`
FixedMaskLength int `json:"fixed_mask_length" yaml:"fixed_mask_length"`
ExactFieldMatch bool `json:"exact_field_match" yaml:"exact_field_match"`
EnableDefaultPatterns bool `json:"enable_default_patterns" yaml:"enable_default_patterns"`
}
LogDesensitization contains log masking settings.
type Logger ¶
type Logger struct {
Level int `json:"level" yaml:"level"`
Path string `json:"path" yaml:"path"`
Format string `json:"format" yaml:"format"`
Output string `json:"output" yaml:"output"`
OutputFile string `json:"output_file" yaml:"output_file"`
IndexName string `json:"index_name" yaml:"index_name"`
DateSuffix string `json:"date_suffix" yaml:"date_suffix"`
RotateDaily bool `json:"rotate_daily" yaml:"rotate_daily"`
Desensitization *LogDesensitization `json:"desensitization" yaml:"desensitization"`
Meilisearch *LoggerMeilisearch `json:"meilisearch" yaml:"meilisearch"`
Elasticsearch *LoggerElasticsearch `json:"elasticsearch" yaml:"elasticsearch"`
OpenSearch *LoggerOpenSearch `json:"opensearch" yaml:"opensearch"`
}
Logger contains logging infrastructure settings.
func GetLoggerConfig ¶ added in v0.2.5
GetLoggerConfig returns logging configuration from viper.
func ProvideLoggerConfig ¶ added in v0.2.0
ProvideLoggerConfig provides the logger configuration.
func (*Logger) BuildIndexName ¶ added in v0.2.5
BuildIndexName builds the date-qualified log index name.
func (*Logger) GetCurrentIndexName ¶ added in v0.2.5
GetCurrentIndexName returns the log index name for the current date.
type LoggerElasticsearch ¶ added in v0.2.5
type LoggerElasticsearch struct {
Addresses []string `json:"addresses" yaml:"addresses"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
}
LoggerElasticsearch contains Elasticsearch log hook settings.
type LoggerMeilisearch ¶ added in v0.2.5
type LoggerMeilisearch struct {
Host string `json:"host" yaml:"host"`
APIKey string `json:"api_key" yaml:"api_key"`
}
LoggerMeilisearch contains Meilisearch log hook settings.
type LoggerOpenSearch ¶ added in v0.2.5
type LoggerOpenSearch struct {
Addresses []string `json:"addresses" yaml:"addresses"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
InsecureSkipTLS bool `json:"insecure_skip_tls" yaml:"insecure_skip_tls"`
}
LoggerOpenSearch contains OpenSearch log hook settings.
type MailgunConfig ¶ added in v0.2.5
type MailgunConfig struct {
Key string `json:"key" yaml:"key"`
Domain string `json:"domain" yaml:"domain"`
From string `json:"from" yaml:"from"`
}
MailgunConfig contains Mailgun credentials and sender settings.
type NetEaseConfig ¶ added in v0.2.5
type NetEaseConfig struct {
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
From string `json:"from" yaml:"from"`
SMTPHost string `json:"smtp_host" yaml:"smtp_host"`
SMTPPort string `json:"smtp_port" yaml:"smtp_port"`
}
NetEaseConfig contains NetEase SMTP credentials and endpoint settings.
type OAuth ¶
type OAuth struct {
Providers map[string]*OAuthProvider `json:"providers" yaml:"providers"`
DefaultScope []string `json:"default_scope" yaml:"default_scope"`
EnablePKCE bool `json:"enable_pkce" yaml:"enable_pkce"`
StateSecret string `json:"state_secret" yaml:"state_secret"`
}
OAuth contains OAuth infrastructure settings.
func GetOAuthConfig ¶ added in v0.2.5
GetOAuthConfig loads OAuth configuration from viper.
func ProvideOAuthConfig ¶ added in v0.2.0
ProvideOAuthConfig provides the OAuth configuration.
type OAuthProvider ¶ added in v0.2.5
type OAuthProvider struct {
ClientID string `json:"client_id" yaml:"client_id"`
ClientSecret string `json:"client_secret" yaml:"client_secret"`
RedirectURL string `json:"redirect_url" yaml:"redirect_url"`
Scopes []string `json:"scopes" yaml:"scopes"`
AuthURL string `json:"auth_url" yaml:"auth_url"`
TokenURL string `json:"token_url" yaml:"token_url"`
UserInfoURL string `json:"user_info_url" yaml:"user_info_url"`
RevokeURL string `json:"revoke_url" yaml:"revoke_url"`
Enabled bool `json:"enabled" yaml:"enabled"`
ExtraParams map[string]string `json:"extra_params" yaml:"extra_params"`
}
OAuthProvider contains provider-specific OAuth settings.
type SMTPConfig ¶ added in v0.2.5
type SMTPConfig struct {
SMTPHost string `json:"host" yaml:"host"`
SMTPPort string `json:"port" yaml:"port"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
From string `json:"from" yaml:"from"`
}
SMTPConfig contains generic SMTP credentials and endpoint settings.
type SendGridConfig ¶ added in v0.2.5
type SendGridConfig struct {
Key string `json:"key" yaml:"key"`
From string `json:"from" yaml:"from"`
}
SendGridConfig contains SendGrid API credentials and sender settings.
type Sentry ¶
type Sentry struct {
Endpoint string `json:"endpoint" yaml:"endpoint"`
Environment string `json:"environment" yaml:"environment"`
Release string `json:"release" yaml:"release"`
SampleRate float64 `json:"sample_rate" yaml:"sample_rate"`
}
Sentry contains Sentry error tracking infrastructure settings.
func GetSentryConfig ¶ added in v0.2.5
GetSentryConfig returns Sentry configuration from viper when configured.
func ProvideSentryConfig ¶ added in v0.2.5
ProvideSentryConfig provides Sentry error tracking configuration.
type Storage ¶
type Storage struct {
Provider string `json:"provider" yaml:"provider"`
ID string `json:"id" yaml:"id"`
Secret string `json:"secret" yaml:"secret"`
Region string `json:"region" yaml:"region"`
Bucket string `json:"bucket" yaml:"bucket"`
Endpoint string `json:"endpoint" yaml:"endpoint"`
ServiceAccountJSON string `json:"service_account_json,omitempty" yaml:"service_account_json,omitempty"`
OtpCode string `json:"otp_code,omitempty" yaml:"otp_code,omitempty"`
Debug bool `json:"debug,omitempty" yaml:"debug,omitempty"`
AppID string `json:"app_id,omitempty" yaml:"app_id,omitempty"`
}
Storage contains object storage infrastructure settings.
func ProvideStorageConfig ¶ added in v0.2.0
ProvideStorageConfig provides the storage configuration.
type TencentCloudConfig ¶ added in v0.2.5
type TencentCloudConfig struct {
ID string `json:"id" yaml:"id"`
Secret string `json:"secret" yaml:"secret"`
From string `json:"from" yaml:"from"`
}
TencentCloudConfig contains Tencent Cloud email credentials and sender settings.
type Tracing ¶ added in v0.2.5
type Tracing struct {
Endpoint string `json:"endpoint" yaml:"endpoint"`
ServiceName string `json:"service_name" yaml:"service_name"`
ServiceVersion string `json:"service_version" yaml:"service_version"`
Environment string `json:"environment" yaml:"environment"`
SamplingRate float64 `json:"sampling_rate" yaml:"sampling_rate"`
MaxExportBatchSize int `json:"max_export_batch_size" yaml:"max_export_batch_size"`
BatchTimeout time.Duration `json:"batch_timeout" yaml:"batch_timeout"`
ExportTimeout time.Duration `json:"export_timeout" yaml:"export_timeout"`
MaxQueueSize int `json:"max_queue_size" yaml:"max_queue_size"`
MaxAttributes int `json:"max_attributes" yaml:"max_attributes"`
MaxAttributeLength int `json:"max_attribute_length" yaml:"max_attribute_length"`
MaxEventsPerSpan int `json:"max_events_per_span" yaml:"max_events_per_span"`
MaxLinksPerSpan int `json:"max_links_per_span" yaml:"max_links_per_span"`
TLSEnabled bool `json:"tls_enabled" yaml:"tls_enabled"`
InsecureSkipVerify bool `json:"insecure_skip_verify" yaml:"insecure_skip_verify"`
TLSCertFile string `json:"tls_cert_file" yaml:"tls_cert_file"`
TLSKeyFile string `json:"tls_key_file" yaml:"tls_key_file"`
TLSCAFile string `json:"tls_ca_file" yaml:"tls_ca_file"`
Headers map[string]string `json:"headers" yaml:"headers"`
}
Tracing contains OpenTelemetry tracing infrastructure settings.
func GetTracingConfig ¶ added in v0.2.5
GetTracingConfig returns OpenTelemetry tracing configuration from viper when configured.
func ProvideTracingConfig ¶ added in v0.2.5
ProvideTracingConfig provides OpenTelemetry tracing configuration.