appconf

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2024 License: MIT Imports: 10 Imported by: 0

README

Appconf for Go

Build and Test State Go Reference MIT License

The appconf module is a lightweight Go configuration solution. It supports

  • setting defaults
  • reading from JSON files
  • reading from environment variables
  • reading from command line flags

Installation

go get github.com/daemotron/appconf

Usage

package main

import (
    "github.com/daemotron/appconf"
    "log"
)

func main() {
    // initialize configuration context
    conf := appconf.NewConf("MyApp")
    
    // register configuration option
    err := conf.NewOption("foo", appconf.WithDefaultString("bar"), appconf.WithFlag("f"))
    if err != nil {
        log.Fatalf("Error: %v", err)
    }
	
    // update configuration from files, environment and command line flags
    err = conf.Update()
    if err != nil {
        log.Fatalf("Error: %v", err)
    }
}

Conventions

The appconf module relies on several conventions in order to keep its interface lean and simple.

Configuration Files

The appconf module uses the provided App Name (as well as App Author and App Version if provided) to make assumptions about possible configuration file paths and names.

It expects to find configuration files in one of the directories provided by

conf.ConfigDirs(true)

and have a name of config.json, conf.json or strings.ToLower(conf.Name) + ".json"

Actually existing configuration files can be listed this way:

configFiles, err := conf.ConfigFiles()

What about Viper

Viper is a highly sophisticated configuration solution, offering far more flexibility. However, Viper also comes with a large amount of dependencies, while appconf only uses packages from Go's standard library.

Documentation

Overview

Package appconf is a lightweight configuration solution for Go applications. It helps manage configuration settings and handle configuration inputs from different sources.

Currently, this package supports the following configuration sources:

  • JSON Files
  • Environment Variables
  • Command Line Flags

Configuration directives are interpreted following this precedence order:

  1. Command Line Flags
  2. Environment Variables
  3. Configuration File
  4. Default Values

Settings provided by an instance with a lower precedence order (i.e. higher priority) will always override those with a higher precedence order (i.e. lower priority).

Index

Constants

This section is empty.

Variables

View Source
var ErrAllUsersProfileNotDefined = errors.New("ALLUSERSPROFILE environment not defined")

The ErrAllUsersProfileNotDefined custom error is raised when the %ALLUSERSPROFILE% environment is not defined (Windows only)

View Source
var ErrFlagsAlreadyParsed = errors.New("flags have already been parsed")

The ErrFlagsAlreadyParsed custom error is raised when flag.Parse() has already been called

View Source
var ErrInvalidType = errors.New("invalid data type")

The ErrInvalidType custom error is raised when a datum cannot be cast

View Source
var ErrOptionDoesNotExist = errors.New("option with this key does not exist")

The ErrOptionDoesNotExist custom error is raised when a requested option key does not exist

View Source
var ErrOptionExists = errors.New("option with this key already exists")

The ErrOptionExists custom error is raised when an option with the same key already exists

Functions

This section is empty.

Types

type AppConf

type AppConf struct {
	Options   map[string]*Option
	ConfFiles []string
	Name      string
	Author    string
	Version   string
	Roaming   bool
}

An AppConf instance represents a configuration context for an application.

func NewConf

func NewConf(appName string, options ...AppOption) *AppConf

NewConf creates a new AppConf context

func (*AppConf) ConfigDirs

func (conf *AppConf) ConfigDirs(multiPath bool) ([]string, error)

ConfigDirs returns the list of all possible configuration dirs for this application, combining UserConfigDir, SiteConfigDir and GlobalConfigDir.

func (*AppConf) ConfigFiles

func (conf *AppConf) ConfigFiles() ([]string, error)

ConfigFiles returns a list of all detected configuration files for this application

func (*AppConf) GetBool added in v0.2.0

func (conf *AppConf) GetBool(key string) (bool, error)

GetBool returns the bool value associated with a configuration option

func (*AppConf) GetDefaultBool added in v0.2.0

func (conf *AppConf) GetDefaultBool(key string) (bool, error)

GetDefaultBool returns the default bool value associated with a configuration option

func (*AppConf) GetDefaultFloat added in v0.2.0

func (conf *AppConf) GetDefaultFloat(key string) (float64, error)

GetDefaultFloat returns the default float value associated with a configuration option

func (*AppConf) GetDefaultInt added in v0.2.0

func (conf *AppConf) GetDefaultInt(key string) (int, error)

GetDefaultInt returns the default integer value associated with a configuration option

func (*AppConf) GetDefaultString added in v0.2.0

func (conf *AppConf) GetDefaultString(key string) (string, error)

GetDefaultString returns the default string value associated with a configuration option

func (*AppConf) GetFloat added in v0.2.0

func (conf *AppConf) GetFloat(key string) (float64, error)

GetFloat returns the float value associated with a configuration option

func (*AppConf) GetInt added in v0.2.0

func (conf *AppConf) GetInt(key string) (int, error)

GetInt returns the integer value associated with a configuration option

func (*AppConf) GetString added in v0.2.0

func (conf *AppConf) GetString(key string) (string, error)

GetString returns the string value associated with a configuration option

func (*AppConf) GlobalCacheDir

func (conf *AppConf) GlobalCacheDir() (string, error)

GlobalCacheDir returns the full path to the global cache dir for this application.

Typical global cache directories are:

macOS:      /Library/Caches/<AppName>
Unix:       /var/cache/<AppName>
Windows:    same as [UserCacheDir]

This method is mostly geared towards Unix; on Windows it is identical to SiteDataDir.

func (*AppConf) GlobalConfigDir

func (conf *AppConf) GlobalConfigDir(multiPath bool) (string, error)

GlobalConfigDir returns the full path to the global config dir for this application.

Typical global config directories are:

macOS:      same as SiteConfigDir
Unix:       /etc/<AppName>
Windows:    same as SiteConfigDir

This method is mostly geared towards Unix; on Windows it is identical to SiteDataDir.

func (*AppConf) GlobalDataDir

func (conf *AppConf) GlobalDataDir() (string, error)

GlobalDataDir returns the full path to the global data dir for this application.

Typical site data directories are:

macOS:      /Library/Application Support/<AppName>
Unix:       /var/lib/<AppName>
Windows:    C:\ProgramData\<AppAuthor>\<AppName>   # Hidden, but writeable on Win 7.

This method is mostly geared towards Unix; on Windows it is identical to [SiteDataDir].

func (*AppConf) NewOption

func (conf *AppConf) NewOption(key string, options ...OptOption) error

NewOption creates and registers a new Option within the AppConf context

func (*AppConf) SetBool added in v0.2.0

func (conf *AppConf) SetBool(key string, value bool) error

SetBool sets the bool value associated with a configuration option

func (*AppConf) SetFloat added in v0.2.0

func (conf *AppConf) SetFloat(key string, value float64) error

SetFloat sets the float64 value associated with a configuration option

func (*AppConf) SetInt added in v0.2.0

func (conf *AppConf) SetInt(key string, value int) error

SetInt sets the integer value associated with a configuration option

func (*AppConf) SetString added in v0.2.0

func (conf *AppConf) SetString(key string, value string) error

SetString sets the string value associated with a configuration option

func (*AppConf) SiteConfigDir

func (conf *AppConf) SiteConfigDir(multiPath bool) (string, error)

SiteConfigDir returns the full path to the user-shared config dir for this application.

Typical site config directories are:

macOS:      /Library/Preferences/<AppName>
Unix:       /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in $XDG_CONFIG_DIRS
Windows:    same as SiteDataDir

For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if conf.Multi = False

func (*AppConf) SiteDataDir

func (conf *AppConf) SiteDataDir(multiPath bool) (string, error)

SiteDataDir returns the full path to the user-shared data dir for this application.

Typical site data directories are:

macOS:      /Library/Application Support/<AppName>
Unix:       /usr/local/share/<AppName> or /usr/share/<AppName>
Windows:    C:\ProgramData\<AppAuthor>\<AppName>   # Hidden, but writeable on Win 7.

For Unix, this is using the $XDG_DATA_DIRS[0] default.

func (*AppConf) Update

func (conf *AppConf) Update() error

Update updates options from configuration files, environment variables and command line flags

func (*AppConf) UpdateFromEnv

func (conf *AppConf) UpdateFromEnv() error

UpdateFromEnv updates configuration option values from environment variables

func (*AppConf) UpdateFromFiles

func (conf *AppConf) UpdateFromFiles() error

UpdateFromFiles updates configuration options from all detected configuration files.

WARNING:

This method does not guarantee a certain order. If two configuration files contain
the same keys, it is random which of the files is parsed last, overwriting values
read from files parsed earlier.

func (*AppConf) UpdateFromFlags

func (conf *AppConf) UpdateFromFlags() error

UpdateFromFlags updates configuration options from command line flags

func (*AppConf) UserCacheDir

func (conf *AppConf) UserCacheDir() (string, error)

UserCacheDir returns the full path to the user-specific cache dir for this application.

Typical user cache directories are:

macOS:      ~/Library/Caches/<AppName>
Unix:       ~/.cache/<AppName> (XDG default)
Windows:    C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache

For Unix, we follow the XDG spec and support $XDG_CACHE_HOME. That means, by default "~/.cache/<AppName>"

func (*AppConf) UserConfigDir

func (conf *AppConf) UserConfigDir() (string, error)

UserConfigDir returns the full path to the user-specific config dir for this application.

Typical user config directories are:

macOS:      ~/Library/Preferences/<AppName>
Unix:       ~/.config/<AppName>     # or in $XDG_CONFIG_HOME, if defined
Windows:    same as user_data_dir

For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by default "~/.config/<AppName>".

func (*AppConf) UserDataDir

func (conf *AppConf) UserDataDir() (string, error)

UserDataDir returns the full path to the user-specific directory for this application

Typical user data directories are:

macOS:                  ~/Library/Application Support/<AppName>
Unix:                   ~/.local/share/<AppName>    # or in $XDG_DATA_HOME, if defined
Windows (not roaming):  C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
Windows (roaming):      C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>

For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/<AppName>".

func (*AppConf) UserLogDir

func (conf *AppConf) UserLogDir() (string, error)

UserLogDir returns the full path to the user-specific log dir for this application.

Typical user log directories are:

macOS:      ~/Library/Logs/<AppName>
Unix:       ~/.cache/<AppName>/log  # or under $XDG_CACHE_HOME if defined
Windows:    C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs

func (*AppConf) UserStateDir

func (conf *AppConf) UserStateDir() (string, error)

UserStateDir returns the full path to the user-specific state dir for this application.

Typical user state directories are:

macOS:     same as UserDataDir
Unix:      ~/.local/state/<AppName>   # or in $XDG_STATE_HOME, if defined
Windows:   same as UserDataDir

For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state> to extend the XDG spec and support $XDG_STATE_HOME. That means, by default "~/.local/state/<AppName>".

type AppOption

type AppOption func(*AppConf)

A AppOption is a functional option for configuring an AppConf context

func WithAuthor

func WithAuthor(author string) AppOption

WithAuthor sets the application author or publisher

func WithConfFile

func WithConfFile(confFile string) AppOption

WithConfFile sets a single configuration file to be read

func WithConfFiles

func WithConfFiles(confFiles []string) AppOption

WithConfFiles sets a list of configuration files to be read

func WithRoaming

func WithRoaming() AppOption

WithRoaming sets the roaming flag (applies to Windows only)

func WithVersion

func WithVersion(version string) AppOption

WithVersion sets the application version

type BoolValue

type BoolValue bool

A BoolValue represents a bool configuration value

func (*BoolValue) Copy

func (bv *BoolValue) Copy() Value

Copy creates a deep copy of the bool value.

func (*BoolValue) FromString

func (bv *BoolValue) FromString(value string) error

FromString updates the value from a string.

func (*BoolValue) ToBool

func (bv *BoolValue) ToBool() (bool, error)

ToBool returns the bool representation of the value.

func (*BoolValue) ToFloat64

func (bv *BoolValue) ToFloat64() (float64, error)

ToFloat64 returns the float64 representation of the value.

func (*BoolValue) ToInt

func (bv *BoolValue) ToInt() (int, error)

ToInt returns the int representation of the value.

func (*BoolValue) ToString

func (bv *BoolValue) ToString() string

ToString returns the string representation of the value

type FloatValue

type FloatValue float64

A FloatValue represents a float64 configuration value

func (*FloatValue) Copy

func (fv *FloatValue) Copy() Value

Copy creates a deep copy of the float value.

func (*FloatValue) FromString

func (fv *FloatValue) FromString(value string) error

FromString updates the value from a string.

func (*FloatValue) ToBool

func (fv *FloatValue) ToBool() (bool, error)

ToBool returns the bool representation of the value.

func (*FloatValue) ToFloat64

func (fv *FloatValue) ToFloat64() (float64, error)

ToFloat64 returns the float64 representation of the value.

func (*FloatValue) ToInt

func (fv *FloatValue) ToInt() (int, error)

ToInt returns the int representation of the value.

func (*FloatValue) ToString

func (fv *FloatValue) ToString() string

ToString returns the string representation of the value

type IntValue

type IntValue int

An IntValue represents an int configuration value

func (*IntValue) Copy

func (iv *IntValue) Copy() Value

Copy creates a deep copy of the int value.

func (*IntValue) FromString

func (iv *IntValue) FromString(value string) error

FromString updates the value from a string.

func (*IntValue) ToBool

func (iv *IntValue) ToBool() (bool, error)

ToBool returns the bool representation of the value.

func (*IntValue) ToFloat64

func (iv *IntValue) ToFloat64() (float64, error)

ToFloat64 returns the float64 representation of the value.

func (*IntValue) ToInt

func (iv *IntValue) ToInt() (int, error)

ToInt returns the int representation of the value.

func (*IntValue) ToString

func (iv *IntValue) ToString() string

ToString returns the string representation of the value

type OptOption

type OptOption func(option *Option)

A OptOption is a functional option for configuring an Option object

func WithDefaultBool

func WithDefaultBool(value bool) OptOption

WithDefaultBool sets the default bool value for an option

func WithDefaultFloat

func WithDefaultFloat(value float64) OptOption

WithDefaultFloat sets the default float64 value for an option

func WithDefaultInt

func WithDefaultInt(value int) OptOption

WithDefaultInt sets the default int value for an option

func WithDefaultString

func WithDefaultString(value string) OptOption

WithDefaultString sets the default string value for an option

func WithEnv

func WithEnv(env string) OptOption

WithEnv sets the environment variable for an option

func WithFlag

func WithFlag(flag string) OptOption

WithFlag sets the command line flag for an option

func WithHelp

func WithHelp(help string) OptOption

WithHelp sets the help text for an option

func WithJson

func WithJson(json string) OptOption

WithJson sets the JSON address for an option

type Option

type Option struct {
	Key     string // Key identifies the option and shall be unique
	Default Value  // Default represents the default option value
	Value   Value  // Value represents the current option value
	Flag    string // Flag represents the option's command line flag
	Json    string // Json represents the option's JSON address
	Env     string // Env represents the option's environment variable
	Help    string // Help represents a help string describing the option
}

An Option represents a configuration option

type StringValue

type StringValue string

A StringValue represents a string configuration value

func (*StringValue) Copy

func (sv *StringValue) Copy() Value

Copy creates a deep copy of the string value.

func (*StringValue) FromString

func (sv *StringValue) FromString(value string) error

FromString updates the value from a string.

func (*StringValue) ToBool

func (sv *StringValue) ToBool() (bool, error)

ToBool returns the bool representation of the value.

func (*StringValue) ToFloat64

func (sv *StringValue) ToFloat64() (float64, error)

ToFloat64 returns the float64 representation of the value.

func (*StringValue) ToInt

func (sv *StringValue) ToInt() (int, error)

ToInt returns the int representation of the value.

func (*StringValue) ToString

func (sv *StringValue) ToString() string

ToString returns the string representation of the value.

type Value

type Value interface {
	ToString() string
	ToInt() (int, error)
	ToFloat64() (float64, error)
	ToBool() (bool, error)
	Copy() Value
	FromString(string) error
}

A Value instance represents a generic configuration value and can be of one of these types:

  • string
  • int
  • float64
  • bool

Please note: this is an abstract interface, use the type-specific implementations to actually handle configuration values

Jump to

Keyboard shortcuts

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