conflib

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2024 License: AGPL-3.0 Imports: 10 Imported by: 0

README

conflib

yet another configuration library

conflib is a small library to load configuration from environment variables or disk. Desired configuration is defined in a struct, then populated from a list of potential files, as well as environment variables.

Let's look at example usage:

package main

import (
	"log"

	"git.janky.solutions/finn/conflib"
)

type Config struct {
	Sample    string `env:"SAMP"`
	MyExample int    `default:"9"`
	Nested    NestedConfig
}

type NestedConfig struct {
	SomeVariable string
}

func main() {
	config, err := conflib.Load[Config]("/etc/myapp.json", "myapp.json")
	if err != nil {
		log.Fatal(err)
	}

	log.Println("loaded config: ", config)
}

This will attempt to read /etc/myapp.json and myapp.json and unmarshal them into a Config struct. It will also check for environment variables that match the struct field names, unless overwridden. So the Sample field will be populated from the SAMP environment variable due to the env tag on that field. config.MyExample will be populated from environment variable MY_EXAMPLE, and config.Nested.SomeVariable will be populated by environment variable NESTED_SOME_VARIABLE. If none of the listed files are found and no environment variables match any field, an error will be returned.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Load

func Load[C any](filenames ...string) (C, error)

Load configuration from files or environment variables

func RegisterParser

func RegisterParser(ext string, parser FileParser)

RegisterParser registers a file parser for a particular extension

Types

type FileParser

type FileParser func(target any, f io.Reader) error

type Loader

type Loader[C any] struct {
	// AllowNoSources supresses errors when no configuration data sources can be found. When set to false (default), if none of the listed config files are found and no environment variables match config struct field names, an error will be returned
	AllowNoSources bool

	// EnvPrefix sets the prefix for environment variables to load from. Will be suffixed with an underscore (_) before field names
	EnvPrefix string
}

func (Loader[C]) Load

func (l Loader[C]) Load(filenames ...string) (C, error)

Jump to

Keyboard shortcuts

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