configloader

package module
v0.0.0-...-81079bb Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Unlicense Imports: 8 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ConfigLoader: Dynamic Configuration Management in Go

ConfigLoader is a flexible and powerful library for managing configurations in Go applications. It allows loading, merging, and dynamically overriding configurations from various sources with ease. This makes it an ideal choice for applications that require a high level of flexibility in their configuration management.

Features

  • Load configuration from files with support for JSON, YAML, TOML, and environment variables.
  • Override configuration values programmatically to cater to different environments or runtime requirements.
  • Support for deserializing nested structures and arrays/slices in configurations.
  • Easy integration with existing Go projects with minimal setup.

Getting Started

To use ConfigLoader, first ensure you have it installed:

import "github.com/snippetaccumulator/configloader"
Basic Usage

The following example demonstrates how to load a configuration file:

package main

import (
    "github.com/snippetaccumulator/configloader"
    "log"
)

type AppConfig struct {
    Field1 string
    Field2 int
    Nested struct {
        Field3 bool
    }
}

func main() {
    var config AppConfig
    loader := configloader.NewConfigLoader("config.yaml", configloader.WithPath("/path/to/config/"), configloader.WithDeserializer(new(configloader.YAMLDeserializer)))
    if err := loader.Load(&config); err != nil {
        log.Fatalf("Failed to load configuration: %s", err)
    }
    log.Println("Configuration loaded successfully:", config)
}
Paths

When using deserializers, the data must follow the path of the corresponding tags used by the deserializer. This is obvious for most structures, except for structs with embedded members. Here is an example of how to handle this:

type GenericConfig struct {
    Field1 string
    Field2 int
}

type WebConfig struct {
    GenericConfig
    Port int
}

With the YAML deserializer, the configuration file would need to look like this:

GenericConfig:
  Field1: "value1"
  Field2: 42
Port: 8080

This does not apply for overrides or the mock loader (they use the same code behind the scenes). With overrides one can either use the path with or without the embedded struct name. Meaning both

loader.Override("Field1", "new value")
// and
loader.Override("GenericConfig.Field1", "new value")

are valid. Overrides/MockLoader also needs to match the field names exactly, they do not account for any tags.

Applying Overrides

You can override specific fields of the configuration, useful for setting dynamic values or secrets:

loader.Override("Nested.Field3", false)
if err := loader.Load(&config); err != nil {
    log.Fatalf("Failed to apply overrides: %s", err)
}
Working with Overrides and Deserializers

ConfigLoader supports multiple deserializers out of the box. Here's how you can use an override file with a custom deserializer:

loader := configloader.NewConfigLoader("main_config.yaml",
    configloader.WithPath("/path/to/config/"),
    configloader.WithDeserializer(new(configloader.JSONDeserializer)),
    configloader.WithOverrideFile("/path/to/overrides/", "override_config.yaml"),
    configloader.WithOverrideDeserializer(new(configloader.YAMLDeserializer)),
)

Testing with MockLoader

For testing purposes, ConfigLoader provides a MockLoader to simulate loading configurations without file dependencies:

mockData := map[string]interface{}{
    "Field1": "mockValue",
    "Nested.Field3": true,
}
loader := configloader.NewMockLoader(mockData)
var config AppConfig
if err := loader.Load(&config); err != nil {
    log.Fatalf("Failed to load mock configuration: %s", err)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConfigLoader

type ConfigLoader struct {
	Name                 string
	Path                 string
	OverrideName         string
	OverridePath         string
	Deserializer         DeserializerFunc
	OverrideDeserializer DeserializerFunc
	Overrides            map[string]any
}

ConfigLoader is a struct designed to load and apply configurations from various sources. It supports loading main configuration and override configuration from specified paths and filenames, applying deserializers for each configuration format, and dynamically overriding specific configuration fields via a map of paths to values. Fields include Name, Path, OverrideName, OverridePath for file locations, Deserializer, and OverrideDeserializer for handling specific data formats, and Overrides for field-specific overrides.

func NewConfigLoader

func NewConfigLoader(name string, options ...Option) *ConfigLoader

NewConfigLoader creates and returns a new instance of ConfigLoader with the specified name. It initializes the ConfigLoader's fields with default values: current directory for Path, empty for OverrideName and OverridePath, nil for Deserializer and OverrideDeserializer, and an empty map for Overrides. Additional configurations can be applied using Option functions passed as arguments to this function, allowing for customization of the loader's behavior and settings.

func (*ConfigLoader) Load

func (c *ConfigLoader) Load(config any) error

Load reads the main configuration file based on the ConfigLoader's Path and Name, deserializes it into the provided config object using the set Deserializer, and applies any Overrides. If OverridePath and OverrideName are set, it also loads and applies an override configuration file using either the OverrideDeserializer or the main Deserializer if no OverrideDeserializer is set. Errors during file reading, deserialization, or field setting are returned. This method facilitates the flexible loading and merging of configurations with optional overrides to tailor application settings dynamically.

func (*ConfigLoader) Override

func (c *ConfigLoader) Override(path string, value any) error

Override adds or updates a specific configuration override by path. The path should specify the target field within the configuration object, and the value is what will be set for this field when applying overrides. This method allows for dynamic adjustments to the configuration, even after the initial loading process.

type DeserializerFunc

type DeserializerFunc interface {
	Deserialize(data []byte, v any) error
}

DeserializerFunc outlines the interface for deserializing data from a byte slice into a Go struct. It necessitates an implementation of the Deserialize method, which should interpret the provided byte slice according to the deserializer's format (e.g., JSON, YAML, TOML, etc.) and populate the passed-in struct accordingly. This interface supports flexible data interpretation, facilitating the integration of different configuration file formats.

type EnvDeserializer

type EnvDeserializer struct{}

EnvDeserializer implements the DeserializerFunc interface for environment variable data like .env files.

func (*EnvDeserializer) Deserialize

func (ed *EnvDeserializer) Deserialize(_ []byte, v any) error

type JSONDeserializer

type JSONDeserializer struct{}

JSONDeserializer is a struct with no fields, implementing the DeserializerFunc interface for JSON data. It provides a method to deserialize JSON encoded data into a Go value.

func (*JSONDeserializer) Deserialize

func (jd *JSONDeserializer) Deserialize(data []byte, v any) error

type Loader

type Loader interface {
	Load(config any) error
	Override(path string, value any) error
}

Loader defines the interface for loading configuration data into a Go struct. It requires implementation of the Load method, which takes a configuration object and populates it with data, and the Override method, which allows for dynamic modifications of specific configuration fields after the initial load. This interface is designed to abstract the configuration loading mechanism, enabling the use of various sources and formats.

type MockLoader

type MockLoader struct {
	MockData map[string]any
	// contains filtered or unexported fields
}

func NewMockLoader

func NewMockLoader(mockData map[string]any) *MockLoader

NewMockLoader creates an instance of MockLoader with predefined mock data. This mock loader is designed for testing purposes, allowing developers to simulate the loading of configuration data without accessing actual files. The mock data should be structured as a map representing the configuration fields and their desired values, facilitating easy and controlled testing scenarios.

func (*MockLoader) Load

func (m *MockLoader) Load(config any) error

Load simulates the configuration loading process using predefined mock data. This method attempts to set the configuration fields of the provided config object based on the mock data and any overrides that have been specified. It is designed for testing, allowing developers to verify the behavior of their applications with various configurations without needing to interact with actual configuration files. Returns the first error encountered during field setting if any, otherwise nil.

func (*MockLoader) Override

func (m *MockLoader) Override(path string, value any) error

Override allows for the specification of override values in the mock configuration loading process. This method adds or updates entries in the mock loader's internal overrides map, enabling the testing of configuration behavior when specific fields are modified after the initial mock data load. It's particularly useful for validating how applications handle dynamic configuration changes.

type Option

type Option func(loader *ConfigLoader)

Option defines a function signature for optional configuration functions that customize the behavior of a ConfigLoader instance. These functions enable flexible and modular configuration of a ConfigLoader by setting various parameters such as file paths, deserializers, and override mechanisms. Each option function accepts a pointer to a ConfigLoader instance and modifies it according to the specific needs of the application setup.

func WithDeserializer

func WithDeserializer(deserializer DeserializerFunc) Option

WithDeserializer is an option function for ConfigLoader that sets the specified deserializer function for interpreting the main configuration file. This allows for custom deserialization logic to be applied, enabling the support of various data formats beyond the default ones provided.

func WithOverrideDeserializer

func WithOverrideDeserializer(deserializer DeserializerFunc) Option

WithOverrideDeserializer specifies the deserializer function for the override configuration file. This option allows the ConfigLoader to interpret and apply settings from the override file using a custom deserialization logic, providing the flexibility to handle different data formats for override configurations.

func WithOverrideFile

func WithOverrideFile(path, name string) Option

WithOverrideFile sets the path and name for an override configuration file. This option function enables the ConfigLoader to apply additional configuration settings from a specified file, allowing for flexible adjustments and customization beyond the main configuration. The override file is processed after the main configuration file, with its settings potentially overriding those set by the main configuration.

func WithPath

func WithPath(path string) Option

WithPath configures the path where the main configuration file is located. This option function is intended to be used when creating a new ConfigLoader instance, allowing the specification of a custom directory path for the configuration file, overriding the default current directory.

type TOMLDeserializer

type TOMLDeserializer struct{}

TOMLDeserializer implements the DeserializerFunc interface for TOML data. It provides a method to deserialize TOML encoded data into a Go value.

func (*TOMLDeserializer) Deserialize

func (td *TOMLDeserializer) Deserialize(data []byte, v any) error

type YAMLDeserializer

type YAMLDeserializer struct{}

YAMLDeserializer is a struct with no fields, implementing the DeserializerFunc interface for YAML data. It offers a method to deserialize YAML encoded data into a Go value.

func (*YAMLDeserializer) Deserialize

func (yd *YAMLDeserializer) Deserialize(data []byte, v any) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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