config

package module
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: Apache-2.0 Imports: 13 Imported by: 14

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

View Source
const ExtensionBuiltInMode = "c2hlbgo"

ExtensionBuiltInMode represents the build tag value for built-in extension mode.

Variables

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

func BindConfigToContext(ctx context.Context) context.Context

BindConfigToContext binds the configuration to the context.

func Reload

func Reload() error

Reload reloads the configuration from the file.

func Watch

func Watch(callback func(*Config))

Watch watches the configuration file and reloads it when it changes.

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

func ProvideAuthConfig(cfg *Config) *Auth

ProvideAuthConfig provides the authentication configuration.

type Casbin

type Casbin struct {
	Path  string
	Model string
}

Casbin casbin config struct

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

func GetConfig() (*Config, error)

GetConfig returns the configuration. It does not handle errors internally; instead, it returns the error for the caller to handle.

func Init

func Init() (cfg *Config, err error)

Init initializes and loads the configuration.

func LoadConfig

func LoadConfig(configPath string) (*Config, error)

LoadConfig loads the configuration from the file.

func (*Config) IsProd

func (c *Config) IsProd(envs ...string) bool

IsProd returns current environment is production

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 DBNode

type DBNode = dc.DBNode

DBNode represents a database node

type Data

type Data = dc.Config

Data represents the data configuration

func ProvideDataConfig added in v0.2.0

func ProvideDataConfig(cfg *Config) *Data

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

func ProvideEmailConfig(cfg *Config) *Email

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

func GetExtensionConfig(v *viper.Viper) *Extension

GetExtensionConfig returns extension configuration and panics on invalid values.

func GetExtensionConfigE added in v0.2.5

func GetExtensionConfigE(v *viper.Viper) (*Extension, error)

GetExtensionConfigE returns extension configuration and validation errors.

func ProvideExtensionConfig added in v0.2.0

func ProvideExtensionConfig(cfg *Config) *Extension

ProvideExtensionConfig provides the extension system configuration.

func (*Extension) IsBuiltInMode added in v0.2.5

func (c *Extension) IsBuiltInMode() bool

IsBuiltInMode reports whether built-in extension loading is enabled.

func (*Extension) Validate added in v0.2.5

func (c *Extension) Validate() error

Validate validates extension infrastructure settings.

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 JWT

type JWT struct {
	Secret string
	Expiry time.Duration
}

JWT jwt config struct

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

func GetLoggerConfig(v *viper.Viper) *Logger

GetLoggerConfig returns logging configuration from viper.

func ProvideLoggerConfig added in v0.2.0

func ProvideLoggerConfig(cfg *Config) *Logger

ProvideLoggerConfig provides the logger configuration.

func (*Logger) BuildIndexName added in v0.2.5

func (c *Logger) BuildIndexName(t time.Time) string

BuildIndexName builds the date-qualified log index name.

func (*Logger) GetCurrentIndexName added in v0.2.5

func (c *Logger) GetCurrentIndexName() string

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

func GetOAuthConfig(v *viper.Viper) *OAuth

GetOAuthConfig loads OAuth configuration from viper.

func ProvideOAuthConfig added in v0.2.0

func ProvideOAuthConfig(cfg *Config) *OAuth

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

func GetSentryConfig(v *viper.Viper) *Sentry

GetSentryConfig returns Sentry configuration from viper when configured.

func ProvideSentryConfig added in v0.2.5

func ProvideSentryConfig(cfg *Config) *Sentry

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"`
	SharedFolder       string `json:"shared_folder,omitempty" yaml:"shared_folder,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

func ProvideStorageConfig(cfg *Config) *Storage

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

func GetTracingConfig(v *viper.Viper) *Tracing

GetTracingConfig returns OpenTelemetry tracing configuration from viper when configured.

func ProvideTracingConfig added in v0.2.5

func ProvideTracingConfig(cfg *Config) *Tracing

ProvideTracingConfig provides OpenTelemetry tracing configuration.

Jump to

Keyboard shortcuts

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