config

package
v1.67.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: MIT Imports: 9 Imported by: 3

README

Package config

Пакет config предназначен для работы с конфигурацией приложения с поддержкой:

  • множественных источников данных (yaml, переменные окружения, кастомные источники)
  • валидации конфигурации
  • типизированного доступа к параметрам

Types

Config

Основная структура для работы с конфигурацией.

Methods:

New(opts ...Option) (*Config, error)

Конструктор конфигурации с опциями:

  • WithExtraSource - добавить дополнительные источники, реализующие интерфейс Source
  • WithEnvPrefix - установить префикс для переменных окружения
  • WithValidator - установить валидатор конфигурации, реализующий интерфейс Validator
(c *Config) Set(key string, value any)

Установить новое/перезаписать существующее значение параметра конфигурации.

(c *Config) Delete(key string)

Удалить параметра конфигурации.

(c *Config) Mandatory() Mandatory

Получить обязательные параметры конфигурации.

(c *Config) Optional() Optional

Получить опциональные параметры конфигурации (возвращает значения по-умолчанию).

(c *Config) Read(ptr any) error

Спарсить всю конфигурацию и записать ее по переданному указателю. Если был установлен валидатор, то спаршенная конфигурация будет провалидирована.

YamlFileSource

Создание источника конфигурации из yaml-файла.

(y YamlFileSource) Config() (map[string]string, error)

Получить конфигурацию из yaml-файла в виде мэпы.

Usage

Default usage flow
package main

import (
	"log"
	"time"

	"github.com/txix-open/isp-kit/config"
	"github.com/txix-open/isp-kit/validator"
)

type appConfig struct {
	Host     string `validate:"required"`
	Port     int    `validate:"required"`
	Timeout  time.Duration
	Database struct {
		Dsn string
	}
}

func main() {
	cfg, err := config.New(
		config.WithExtraSource(config.NewYamlConfig("config.yml")),
		config.WithEnvPrefix("APP_"),
		config.WithValidator(validator.Default),
	)
	if err != nil {
		log.Fatal(err)
	}

	var actual appConfig
	err = cfg.Read(&actual)
	if err != nil {
		log.Fatal(err)
	}

	/* access to parameters */
	port := cfg.Mandatory().Int("port")
	timeout := cfg.Optional().Duration("timeout", 5*time.Second)
}

Documentation

Overview

Package config provides a flexible configuration management system with support for multiple sources, environment variable overrides, and type-safe value retrieval.

The package supports reading configuration from YAML files, environment variables, and custom sources. Configuration values can be accessed as mandatory (required) or optional (with defaults) values for common types like strings, integers, booleans, and durations.

Example usage:

cfg, err := config.New(
	config.WithEnvPrefix("MYAPP"),
	config.WithExtraSource(config.NewYamlConfig("config.yaml")),
)
if err != nil {
	log.Fatal(err)
}

// Read mandatory values
host, err := cfg.Mandatory().String("server.host")
port, err := cfg.Mandatory().Int("server.port")

// Read optional values with defaults
timeout := cfg.Optional().Duration("server.timeout", 30*time.Second)

// Decode into a struct
var settings ServerSettings
if err := cfg.Read(&settings); err != nil {
	log.Fatal(err)
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config manages application configuration from multiple sources. It supports loading from YAML files, environment variables, and custom sources, with automatic normalization of keys and value expansion.

func New

func New(opts ...Option) (*Config, error)

New creates a new Config instance with the provided options. It loads configuration from extra sources and environment variables. Environment variables are filtered by the envPrefix if set. Keys are normalized to lowercase for case-insensitive access. Returns an error if any extra source fails to load.

func (*Config) Delete

func (c *Config) Delete(key string)

Delete removes a value by configuration key.

func (*Config) Mandatory

func (c *Config) Mandatory() Mandatory

Mandatory returns a Mandatory accessor for required configuration values. Values accessed through Mandatory will return an error if the key is not found.

func (*Config) Optional

func (c *Config) Optional() Optional

Optional returns an Optional accessor for configuration values with defaults. Values accessed through Optional will return the provided default if the key is not found.

func (*Config) Read

func (c *Config) Read(ptr any) error

Read decodes the configuration into the provided pointer. It uses mapstructure for decoding with support for type conversions (e.g., string to time.Duration). If a Validator is configured, it validates the decoded structure before returning. Returns an error if decoding or validation fails.

func (*Config) Set

func (c *Config) Set(key string, value any)

Set assigns a value to the specified key. The value is converted to a string representation.

type Mandatory

type Mandatory struct {
	// contains filtered or unexported fields
}

Mandatory provides access to required configuration values. All methods return an error if the requested key is not found or cannot be parsed. Keys are normalized to lowercase for case-insensitive access.

func (Mandatory) Bool

func (m Mandatory) Bool(key string) (bool, error)

Bool retrieves a boolean configuration value. Returns an error if the key is not found or the value cannot be parsed as a boolean. Accepts "1", "t", "T", "true", "TRUE", "True", "0", "f", "F", "false", "FALSE", "False".

func (Mandatory) Duration

func (m Mandatory) Duration(key string) (time.Duration, error)

Duration retrieves a time.Duration configuration value. Returns an error if the key is not found or the value cannot be parsed as a duration. Accepts formats like "30s", "1m", "1h30m" as parsed by time.ParseDuration.

func (Mandatory) Int

func (m Mandatory) Int(key string) (int, error)

Int retrieves an integer configuration value. Returns an error if the key is not found or the value cannot be parsed as an integer.

func (Mandatory) String

func (m Mandatory) String(key string) (string, error)

String retrieves a string configuration value. Returns an error if the key is not found.

type Option

type Option func(l *Config)

Option is a function type that configures a Config instance. Used with the functional options pattern to customize Config behavior.

func WithEnvPrefix

func WithEnvPrefix(prefix string) Option

WithEnvPrefix sets the prefix for environment variable filtering. Only environment variables starting with this prefix (case-insensitive) will be loaded. The prefix is stripped from the key name when stored. Example: WithEnvPrefix("MYAPP") will load MYAPP_HOST as "host".

func WithExtraSource

func WithExtraSource(source Source) Option

WithExtraSource adds a configuration source to be loaded before environment variables. Multiple sources can be added and are processed in order.

func WithValidator

func WithValidator(validator Validator) Option

WithValidator sets a Validator for post-decoding configuration validation. The validator is called after Read() decodes the configuration into a struct.

type Optional

type Optional struct {
	// contains filtered or unexported fields
}

Optional provides access to configuration values with defaults. All methods return the provided default value if the key is not found or cannot be parsed. Unlike Mandatory, these methods never return errors.

func (Optional) Bool

func (o Optional) Bool(key string, defValue bool) bool

Bool retrieves a boolean configuration value or returns the default. Returns defValue if the key is not found or the value cannot be parsed as a boolean.

func (Optional) Duration

func (o Optional) Duration(key string, defValue time.Duration) time.Duration

Duration retrieves a time.Duration configuration value or returns the default. Returns defValue if the key is not found or the value cannot be parsed as a duration.

func (Optional) Int

func (o Optional) Int(key string, defValue int) int

Int retrieves an integer configuration value or returns the default. Returns defValue if the key is not found or the value cannot be parsed as an integer.

func (Optional) String

func (o Optional) String(key string, defValue string) string

String retrieves a string configuration value or returns the default. Returns defValue if the key is not found.

type Source

type Source interface {
	Config() (map[string]string, error)
}

Source defines an interface for configuration providers. Implementations should return a flat map of key-value pairs. Nested YAML structures are automatically flattened using dot notation.

type Validator

type Validator interface {
	ValidateToError(value any) error
}

Validator defines an interface for validating configuration values. Implementations should return an error if the configuration structure is invalid.

type YamlFileSource

type YamlFileSource struct {
	// contains filtered or unexported fields
}

YamlFileSource is a configuration source that reads from a YAML file. It supports nested structures which are flattened into dot-notation keys. For example, a YAML key "server.host" will be stored as "server.host".

func NewYamlConfig

func NewYamlConfig(file string) YamlFileSource

NewYamlConfig creates a new YamlFileSource for the specified YAML file. The file path can be absolute or relative to the working directory.

func (YamlFileSource) Config

func (y YamlFileSource) Config() (map[string]string, error)

Config loads and parses the YAML file, returning a flat map of configuration values. Nested YAML structures are flattened using bellows.Flatten. All values are converted to strings. Returns an error if the file cannot be opened or parsed as valid YAML.

Jump to

Keyboard shortcuts

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