rc

package
v1.67.2 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 6 Imported by: 1

README

Package rc

Пакет rc предоставляет механизм управления удалённой конфигурацией с возможностью её обновления, объединения с конфигурацией-переопределением и валидации.

Types

Validator

Интерфейс Validator определяет метод для валидации конфигурации.

Config

Структура Config реализует управление конфигурацией с учётом переопределений, поддерживает блокировки и валидацию.

Methods:

New(validator Validator, overrideData []byte) *Config

Создаёт новый экземпляр Config с указанным валидатором и данными переопределения.

(c *Config) Upgrade(data []byte, newConfigPtr any, prevConfigPtr any) error

Обновляет конфигурацию:

  • объединяет переданные данные с переопределениями,
  • десериализует в newConfigPtr,
  • валидирует конфигурацию,
  • десериализует предыдущую конфигурацию в prevConfigPtr,
  • сохраняет новую конфигурацию как предыдущую.
Functions
Upgrade[T any](rc *Config, data []byte) (newCfg T, prevCfg T, err error)

Удобная обобщённая функция для обновления конфигурации с использованием типа T.

GenerateConfigSchema(cfgPtr any) schema.Schema

Генерирует схему конфигурации для переданной структуры с помощью генератора из пакета rc/schema.

Usage

Default usage flow
import (
    "github.com/txix-open/isp-kit/rc"
)

type MyConfig struct {
    // поля конфигурации
}

type MyValidator struct{}

func (v MyValidator) ValidateToError(value any) error {
    // реализовать валидацию
    return nil
}

func main() {
    validator := MyValidator{}
    overrideData := []byte(`{"some.key":"override value"}`)
    rcConfig := rc.New(validator, overrideData)

    data := []byte(`{"some.key":"value"}`)

    var newCfg, prevCfg MyConfig
    err := rcConfig.Upgrade(data, &newCfg, &prevCfg)
    if err != nil {
        panic(err)
    }
    // newCfg - новая конфигурация
    // prevCfg - предыдущая конфигурация
}

Documentation

Overview

Package rc provides a configuration management system with support for override merging, validation, and hot-reloading capabilities. It uses JSON as the internal format and supports hierarchical configuration through path delimiters.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateConfigSchema

func GenerateConfigSchema(cfgPtr any) schema.Schema

GenerateConfigSchema creates a JSON schema from a configuration struct pointer. It sets the title to "Remote config" and returns the generated schema. The cfgPtr should be a pointer to a struct that represents the configuration.

func Upgrade added in v1.31.0

func Upgrade[T any](rc *Config, data []byte) (newCfg T, prevCfg T, err error)

Upgrade is a generic wrapper for Config.Upgrade that returns typed configuration structs. It unmarshals the new and previous configurations into the generic types T. Returns the new configuration, the previous configuration, and any error encountered.

Types

type Config

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

Config manages configuration state with support for override merging and validation. It is safe for concurrent use.

func New

func New(validator Validator, overrideData []byte) *Config

New creates a new Config instance with the provided validator and override data. The overrideData is merged with new configuration data during upgrades. The default delimiter for hierarchical paths is "~".

func (*Config) Upgrade

func (c *Config) Upgrade(data []byte, newConfigPtr any, prevConfigPtr any) error

Upgrade processes new configuration data by merging it with overrides, unmarshaling into the provided config pointer, and validating the result. If validation succeeds, it stores the new config as the previous config. The prevConfigPtr is populated with the previous configuration state if available. Returns an error if merging, unmarshaling, or validation fails.

type Validator

type Validator interface {
	ValidateToError(value any) error
}

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

Directories

Path Synopsis
Package schema provides JSON schema generation for Go structs with support for custom field properties, validation constraints, and tag-based configuration.
Package schema provides JSON schema generation for Go structs with support for custom field properties, validation constraints, and tag-based configuration.

Jump to

Keyboard shortcuts

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