ezconf

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2024 License: MIT Imports: 14 Imported by: 8

README

EZConf Build Status codecov Go Report Card

Go library to provide simple way of reading configuration settings from four sources, with each source able to override the previous:

  1. The default settings for your app
  2. A TOML file with settings
  3. Environment variables mapping to your top level settings
  4. Command line parameters mapping to your top level settings

To use it, you only need to create a struct representing the desired configuration and create an instance with the defaults for your app. You can then pass that struct to the library and read the settings from all the sources above.

The library will automatically parse command line parameters and environment variables for all top level fields in your struct of the following types:

  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • bool
  • string
  • time.Time as strings in the following formats: 2018-04-02, 15:30:02, 2018-04-02T15:30:02.000 and 2018-04-03T05:30:00.123+07:00
  • slog.Level as strings e.g. info

It converts all CamelCase fields to snake_case in a manner that is compatible with the acronyms we work with everyday. Some examples of how a struct name is converted to a TOML field, environment variable and command line parameter can be found below.

Environment variables are prefixed with your app name, in this case courier:

Struct Field TOML Field Environment Variable Command line Parameter
AWSRegion aws_region COURIER_AWS_REGION aws-region
EC2InstanceID ec2_instance_id COURIER_EC2_INSTANCE_ID ec2-instance-id
DB db COURIER_DB db
NumWorkers num_workers COURIER_NUM_WORKERS num-workers

EZConf will also automatically create the appropriate flags and help based on your struct definition, for example:

% courier -help
Courier - a fast message broker for IP and SMS messages

Usage of courier:
  -aws-region string
    	the aws region that S3 buckets are in (default "us-west-2")
  -db string
    	the url describing how to connect to the database (default "postgres://user@secret:rds-internal.foo.bar/courier")
  -debug-conf
    	print where config values are coming from
  -ec2-instance-id string
    	the id of the ec2 instance we are running on (default "i-12355111134a")
  -help
    	print usage information
  -num-workers int
    	the number of workers to start (default 32)

Environment variables:
          COURIER_AWS_REGION - string
                  COURIER_DB - string
     COURIER_EC2_INSTANCE_ID - string
         COURIER_NUM_WORKERS - int

Example

package main

import (
	"fmt"

	"github.com/nyaruka/ezconf"
)

// Config is our apps configuration struct, we can use the `help` tag to add usage information
type Config struct {
	AWSRegion     string `help:"the aws region that S3 buckets are in"`
	DB            string `help:"the url describing how to connect to the database"`
	EC2InstanceID string `help:"the id of the ec2 instance we are running on"`
	NumWorkers    int    `help:"the number of workers to start"`
}

func main() {
	// instantiate our config with our defaults
	config := &Config{
		AWSRegion:     "us-west-2",
		DB:            "postgres://user@secret:rds-internal.foo.bar/courier",
		EC2InstanceID: "i-12355111134a",
		NumWorkers:    32,
	}

	// create our loader object, configured with configuration struct (must be a pointer), our name
	// and description, as well as any files we want to search for
	loader := ezconf.NewLoader(
		config,
		"courier", "Courier - a fast message broker for IP and SMS messages",
		[]string{"courier.toml"},
	)

	// load our configuration, exiting if we encounter any errors
	loader.MustLoad()

	// our settings have now been loaded into our config struct
	fmt.Printf("Final Settings:\n%+v\n", *config)

	// if we wish we can also validate our config using our favorite validation library
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CamelToSnake

func CamelToSnake(camel string) string

CamelToSnake converts a CamelCase strings to a snake_case using the following algorithm:

  1. for every transition from upper->lowercase insert an underscore before the uppercase character

  2. for every transition fro lowercase->uppercase insert an underscore before the uppercase

  3. lowercase resulting string

    Examples: CamelCase -> camel_case AWSConfig -> aws_config IPAddress -> ip_address S3MediaPrefix -> s3_media_prefix Route53Region -> route53_region CamelCaseA -> camel_case_a CamelABCCaseDEF -> camel_abc_case_def

Types

type EZLoader added in v0.2.1

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

EZLoader allows you to load your configuration from four sources, in order of priority (later overrides earlier):

  1. The default values of your configuration struct
  2. TOML files you specify (optional)
  3. Set environment variables
  4. Command line parameters

func NewLoader added in v0.2.1

func NewLoader(config interface{}, name string, description string, files []string) *EZLoader

NewLoader creates a new EZLoader for the passed in configuration. `config` should be a pointer to a struct. `name` and `description` are used to build environment variables and help parameters. The list of files can be nil, or can contain optional files to read TOML configuration from in priority order. The first file found and parsed will end parsing of others, but there is no requirement that any file is found.

func (*EZLoader) Load added in v0.2.1

func (ez *EZLoader) Load() error

Load loads our configuration from our sources in the order of:

  1. TOML files
  2. Environment variables
  3. Command line parameters

If any error is encountered it is returned for the caller to process.

func (*EZLoader) MustLoad added in v0.2.1

func (ez *EZLoader) MustLoad()

MustLoad loads our configuration from our sources in the order of:

  1. TOML files
  2. Environment variables
  3. Command line parameters

If any error is encountered, the program will exit reporting the error and showing usage.

Jump to

Keyboard shortcuts

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