config

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: Apache-2.0 Imports: 17 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

This section is empty.

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

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 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"`
	Observes    *Observes    `yaml:"observes" json:"observes"`
	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 = email.Email

Email represents the email configuration

func ProvideEmailConfig added in v0.2.0

func ProvideEmailConfig(cfg *Config) *Email

ProvideEmailConfig provides the email configuration.

type Extension

type Extension = ec.Config

Extension represents the extension configuration

func ProvideExtensionConfig added in v0.2.0

func ProvideExtensionConfig(cfg *Config) *Extension

ProvideExtensionConfig provides the extension system configuration.

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 Logger

type Logger = lc.Config

Logger represents the logger configuration

func ProvideLoggerConfig added in v0.2.0

func ProvideLoggerConfig(cfg *Config) *Logger

ProvideLoggerConfig provides the logger configuration.

type OAuth

type OAuth = oc.Config

OAuth represents the OAuth configuration

func ProvideOAuthConfig added in v0.2.0

func ProvideOAuthConfig(cfg *Config) *OAuth

ProvideOAuthConfig provides the OAuth configuration.

type Observes

type Observes struct {
	Sentry *Sentry
	Tracer *Tracer
}

Observes config struct

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 config struct

type Storage

type Storage = oss.Config

func ProvideStorageConfig added in v0.2.0

func ProvideStorageConfig(cfg *Config) *Storage

ProvideStorageConfig provides the storage configuration.

type Tracer

type Tracer struct {
	Endpoint string `json:"endpoint" yaml:"endpoint"` // OTLP gRPC endpoint

	// Service identification
	ServiceName    string `json:"service_name" yaml:"service_name"`
	ServiceVersion string `json:"service_version" yaml:"service_version"`
	Environment    string `json:"environment" yaml:"environment"`

	// Sampling configuration
	SamplingRate float64 `json:"sampling_rate" yaml:"sampling_rate"` // 0.0 to 1.0

	// Performance tuning
	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"`

	// Attribute limits
	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"`

	// TLS configuration
	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 for authentication
	Headers map[string]string `json:"headers" yaml:"headers"`
}

Tracer config struct for OpenTelemetry

Jump to

Keyboard shortcuts

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