config

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: MIT Imports: 14 Imported by: 0

README ΒΆ

πŸ› οΈ go-config: Universal Configuration Library for Go

License Static Badge Coverage Status Go Reference Go Reference

go-config is a universal library for Go that simplifies working with configuration files and data from various sources. The library provides a flexible interface for loading, decoding, and merging configurations.

🌟 Key Features

  • Support for multiple data sources:

    • Command-line arguments
    • Consul KV
    • Environment variables
    • Files
    • Any object implementing the io.Reader interface
  • Flexibility in decoding:

    • Built-in JSON decoder
    • Ability to use third-party decoders (e.g., XML)
  • Configuration merging:

    • Loading configuration from multiple sources
    • Merging strategies: AllOf (all sources must succeed) and OneOf (at least one source succeeds)
  • Additional features:

    • Partial filling of existing structures
    • Simple integration into existing projects

πŸ“¦ Installation

go get github.com/MordaTeam/go-config

πŸš€ Usage

Simple example: Reading configuration from io.Reader
type Config struct {
    Foo string `json:"foo"`
    Bar int    `json:"bar"`
}

source := strings.NewReader(`{"foo": "hello", "bar": 42}`)
cfg, err := config.New[Config](config.FromReader(source))
if err != nil {
    panic(err)
}

fmt.Printf("%+v\n", cfg) // Output: {Foo:hello Bar:42}

By default, the JSON decoder is used.


Using a different format (XML)
type Config struct {
    Sizes []string `xml:"size"`
}

source := strings.NewReader(`
<sizes>
    <size>small</size>
    <size>regular</size>
    <size>large</size>
</sizes>`)

cfg, err := config.New[Config](
    config.FromReader(source),
    config.WithDecoder(xml.NewDecoder),
)
if err != nil {
    panic(err)
}

fmt.Printf("%+v\n", cfg) // Output: {Sizes:[small regular large]}

Partially filling an existing configuration

If you already have a partially filled structure, you can fill it further:

type Config struct {
    Foo string `json:"foo"`
    Bar string `json:"bar"`
}

source := strings.NewReader(`{"bar": "hello"}`)
cfg := Config{
    Foo: "initialized",
}

if err := config.Fill(&cfg, config.FromReader(source)); err != nil {
    panic(err)
}

fmt.Printf("%+v\n", cfg) // Output: {Foo:initialized Bar:hello}

Merging configurations from multiple sources
type Config struct {
    Foo   string   `json:"foo"`
    Bar   string   `json:"bar"`
    Sizes []string `xml:"size"`
}

source1 := strings.NewReader(`{"foo": "hello", "bar": "world"}`)
source2 := strings.NewReader(`
<sizes>
    <size>small</size>
    <size>regular</size>
    <size>large</size>
</sizes>`)

cfg, err := config.Multi[Config]().
    Add(config.FromReader(source1)).
    Add(config.FromReader(source2), config.WithDecoder(xml.NewDecoder)).
    AllOf()
if err != nil {
    panic(err)
}

fmt.Printf("%+v\n", cfg) // Output: {Foo:hello Bar:world Sizes:[small regular large]}

The AllOf method requires successful reading from all sources. If at least one successful source is needed, use the OneOf method.


πŸ› οΈ API

Interfaces
  1. ConfigProvider:

    • Responsible for retrieving configuration from a specific source.
    • Implementations:
      • FromCmdline
      • FromConsul
      • FromEnv
      • FromFile
      • FromReader
      • NoProvider
  2. Decoder:

    • Responsible for converting configuration into the desired structure.
    • Supports custom decoders.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var NoProvider = &noProvider{}

NoProvider is a no-op config provider. It always returns empty io.Reader.

Functions ΒΆ

func CmdlineDecoder ΒΆ

func CmdlineDecoder(r io.Reader) *cmdlineDecoder

Returns cmdline decoder that parses cmd args to struct with tags. It uses under the hood jessevdk/go-flags library.

func EnvDecoder ΒΆ

func EnvDecoder(r io.Reader) *envDecoder

Returns env decoder that parses envs to struct with tags. Provider should return json config or nothing. JSON config will be used as additional environment. From JSON config will be read to map[string]string, so variables must be string (other will be ignored). Use this decoder with provider NoProvider if you want variables only from environment. Recommended use with EnvProvider, because it provides variable $HOSTNAME. It uses under the hood caarlos0/env/v9 library.

func Fill ΒΆ

func Fill[T any](cfg *T, provider ConfigProvider, opts ...options.Option[cfgOpts]) error

Fill creates config and fills into cfg argument.

Provider provides data for decoding. By default, it uses decoder json.Decoder. Use WithDecoder to override the decoder. If the reader implements the io.Closer interface, then it will be closed.

For example we want to create config with default values and then fill config.

type Config struct {
	Foo string `json:"foo"`
}

func main() {
	cfg := Config{
		Foo: "default"
	}

	err := config.Fill(&cfg, config.FromConsul"/bar/foo"))
	//...
}

func FromCmdline ΒΆ

func FromCmdline() *cmdlineProvider

Returns config provider that provides config from cmdline arguments.

func FromConsul ΒΆ

func FromConsul(cfgPath string, opts ...ConsulOption) *consulProvider

Returns config provider that provides config from consul kv.

If client wasn't passed with options, it's created with default config.

By default, config will use CONSUL_HTTP_ADDR env as HTTP address. If it's empty, localhost will be chosen.

func FromEnv ΒΆ

func FromEnv() *envProvider

FromEnv returns provider that provides env variables in json form.

Example:

// Env
FOO=bar
BUZ=foo
// converted to
{"FOO": "bar", "BUZ": "foo"}

func FromEnvWithOptions ΒΆ

func FromEnvWithOptions(opts EnvOptions) *envProvider

FromEnvWithOptions returns provider that provides env variables in json form.

Example:

// Env
FOO=bar
BUZ=foo
// converted to
{"FOO": "bar", "BUZ": "foo"}

func FromFile ΒΆ

func FromFile(cfgPath string) *fileProvider

FromFile creates a new config provider from a config file.

func FromReader ΒΆ

func FromReader(r io.Reader) *readerProvider

FromReader returns a ConfigProvider that reads from r.

func IniDecoder ΒΆ added in v1.1.0

func IniDecoder(r io.Reader) *iniDecoder

func Multi ΒΆ

func Multi[T any]() *multiConfigurator[T]

Multi creates multi configurator that aggregates different methods of creating config. Use method .Add to add configurator, then call .OneOf or .AllOf method to build config.

NOTE: result depends on providers order. If parameter is provided by multiple of them, the last wins.

Example

cfg, err := config.Multi[MyConfig]().
	Add(config.FromReader(file)).
	Add(config.FromEnv(), config.WithDecoder(config.EnvDecoder)).
	Add(config.FromCmdline(), config.WithDecoder(config.CmdlineDecoder)).
	AllOf()

func New ΒΆ

func New[T any](provider ConfigProvider, opts ...options.Option[cfgOpts]) (cfg T, err error)

Creates config T where provider provides data for decoding. By default, it uses json.Decoder. Use WithDecoder to override the decoder. If the reader implements the io.Closer interface, then it will be closed.

func WithDecoder ΒΆ

func WithDecoder[D Decoder](newDec func(r io.Reader) D) options.Option[cfgOpts]

WithDecoder is an option that overrides the default decoder. By default, it uses json.Decoder.

Types ΒΆ

type ConfigProvider ΒΆ

type ConfigProvider interface {
	ProvideConfig() (io.Reader, error)
}

ConfigProvider is an interface that provides configuration data.

type ConsulOption ΒΆ

type ConsulOption func(*consulOpts) error

func ConsulWithClient ΒΆ

func ConsulWithClient(client *consul.Client) ConsulOption

Overrides consul client.

func ConsulWithQueryOptions ΒΆ

func ConsulWithQueryOptions(qry *consul.QueryOptions) ConsulOption

Defines the query options that will be used when lookuping for the config.

type Decoder ΒΆ

type Decoder interface {
	Decode(v any) error
}

Decoder is an interface that decodes configuration data into an object. The object must be pointer.

type EnvOptions ΒΆ

type EnvOptions struct {
	// Enable replacing ${var} or $var in the string according to the values of the current environment variables.
	// By default, false.
	ExpandEnv bool

	// Env keys will be converted to lower case (FOO -> foo).
	// By default, false.
	KeyToLowerCase bool
}

Jump to

Keyboard shortcuts

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