confer

package module
v0.0.0-...-9a227d3 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2016 License: MIT Imports: 16 Imported by: 41 modules, 73 packages

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

Confer

Build Status

A viper-derived configuration management package.

Significant changes include:

  • Materialized path access of configuration variables.
  • The singleton has been replaced by separate instances, largely for testability.
  • The ability to load and merge multiple configuration files.

Features

  1. Merging multiple configuration sources.
  config.ReadPaths("application.yaml", "environments/production.yaml")`
  1. Materialized path access of nested configuration data.
  config.GetInt('app.database.port')
  1. Binding of environment variables to configuration data.

    APP_DATABASE_PORT=3456 go run app.go

  2. User-defined helper methods.

Usage

Initialization

Create your configuration instance:

config := confer.NewConfig()

Then set defaults, read paths, set overrides:

config.SetDefault("environment", "development")
config.ReadPaths("application.yaml", "environments/production.yml")
config.Set("environment", "development")

No worries! Confer will conveniently merge deeply nested structures for you. My usual configuration setup looks like this:

config
  ├── application.development.yml
  ├── application.production.yml
  └── application.yml

For example, an application-specific config package like the one below can be used to drive a core configuration with environment specific overrides:


var App *confer.Config

func init() {
  App = confer.NewConfig()
  appenv := os.Getenv("MYAPP_ENV");
  paths := []string{"application.yml"}

  if (appenv != "") {
    paths = append(paths, fmt.Sprintf("application.%s.yml", appenv))
  }

  if err := App.ReadPaths(paths...); err != nil {
    log.Warn(err)
  }
}
Setting Defaults

Sets a value if it hasn't already been set. Multiple invocations won't clobber existing values, so you'll likely want to do this before reading from files.

config := confer.NewConfig()
config.ReadPaths("application.yaml")
config.SetDefault("ContentDir", "content")
config.SetDefault("LayoutDir", "layouts")
config.SetDefault("Indexes", map[string]string{"tag": "tags", "category": "categories"})
Setting Keys / Value Pairs

Sets a value. Has lower precedence than environment variables or command line flags.

config.Set("verbose", true)
config.Set("logfile", "/var/log/config.log")
Getting Values

There are a variety of accessors for accessing type-coerced values:

Get(key string) : interface{}
GetBool(key string) : bool
GetFloat64(key string) : float64
GetInt(key string) : int
GetString(key string) : string
GetStringMap(key string) : map[string]interface{}
GetStringMapString(key string) : map[string]string
GetStringSlice(key string) : []string
GetTime(key string) : time.Time
IsSet(key string) : bool
Deep Configuration Data

Materialized paths allow easy access of deeply nested config data:

logger_config := config.GetStringMap("logger.stdout")

Because periods aren't valid environment variable characters, when using automatic environment bindings (see below), substitute with underscores:

LOGGER_STDOUT=/var/log/myapp go run server.go
Environment Bindings
Automatic Binding

Confer can automatically bind all existing configuration keys to environment variables.

Given some sort of application.yaml

---
app:
   log: "verbose"
   database:
       host: "localhost"

And this pair of calls:

config.ReadPaths("application.yaml")
config.AutomaticEnv()

You'll have the following environment variables exposed for configuration:

APP_LOG
APP_DATABASE_HOST
Selective Binding

If this automatic binding is bizarre, you can selectively bind environment variables with ``BindEnv()`.

config.BindEnv("APP_LOG", "app.log")
Helpers

You can Set a func() interface{} at a configuration key to provide values dynamically:

config.Set("dbstring", func() interface {} {
  return fmt.Sprintf(
    "user=%s dbname=%s sslmode=%s",
    config.GetString("database.user"),
    config.GetString("database.name"),
    config.GetString("database.sslmode"),
  )
})
assert(config.GetString("dbstring") ==  "user=doug dbname=pruden sslmode=pushups")

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

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

Manages key/value access and aliasing across multiple configuration sources.

func NewConfig

func NewConfig() *Config

func (*Config) AllKeys

func (manager *Config) AllKeys() []string

Returns all currently set keys, pruning ancestors and only showing the leaves.

func (*Config) AllSettings

func (manager *Config) AllSettings() map[string]interface{}

func (*Config) AutomaticEnv

func (manager *Config) AutomaticEnv()

Have confer check ENV variables for all keys set in config, default & flags

func (*Config) BindEnv

func (manager *Config) BindEnv(input ...string) (err error)

Binds a confer key to a ENV variable. ENV variables are case sensitive If only

func (*Config) BindPFlag

func (manager *Config) BindPFlag(key string, flag *pflag.Flag) (err error)

Binds a configuration key to a command line flag:

pflag.Int("port", 8080, "The best alternative port")
confer.BindPFlag("port", pflag.Lookup("port"))

func (*Config) Debug

func (manager *Config) Debug()

func (*Config) Find

func (self *Config) Find(key string) interface{}

Finds a value at a provided key, returning nil if the key does not exist. The order of precedence for configuration data is: 1. Program arguments. 2. Environment variables. 3. Config file data, overrides, and defaults.

func (*Config) Get

func (manager *Config) Get(key string) interface{}

Get returns an interface.. Must be typecast or used by something that will typecast

func (*Config) GetBool

func (manager *Config) GetBool(key string) bool

func (*Config) GetFloat64

func (manager *Config) GetFloat64(key string) float64

func (*Config) GetInt

func (manager *Config) GetInt(key string) int

func (*Config) GetString

func (manager *Config) GetString(key string) string

func (*Config) GetStringMap

func (manager *Config) GetStringMap(key string) map[string]interface{}

func (*Config) GetStringMapString

func (manager *Config) GetStringMapString(key string) map[string]string

func (*Config) GetStringSlice

func (manager *Config) GetStringSlice(key string) []string

func (*Config) GetTime

func (manager *Config) GetTime(key string) time.Time

func (*Config) InConfig

func (manager *Config) InConfig(key string) bool

Returns true if the key provided exists in our configuration.

func (*Config) IsSet

func (manager *Config) IsSet(key string) bool

Returns true if the config key exists and is non-nil.

func (*Config) MergeAttributes

func (manager *Config) MergeAttributes(val interface{}) error

Merges data into the our attributes configuration tier from a struct.

func (*Config) ReadPaths

func (manager *Config) ReadPaths(paths ...string) error

Loads and sequentially + recursively merges the provided config arguments. Returns an error if any of the files fail to load, though this may be expecte in the case of search paths.

func (*Config) Set

func (manager *Config) Set(key string, value interface{})

Explicitly sets a value. Will not override command line arguments or environment variables, as those sources have higher precedence.

func (*Config) SetDefault

func (manager *Config) SetDefault(key string, value interface{})

Set the default value for this key. Default only used when no value is provided by the user via flag, config or ENV.

func (*Config) SetRootPath

func (manager *Config) SetRootPath(path string)

Sets an optional root path. This frees you from having to specify a redundant prefix when calling ReadPaths() later.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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