rconfig

package module
v2.2.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2018 License: Apache-2.0 Imports: 11 Imported by: 80

README

Build Status Go Report Card Documentation

Description

Package rconfig implements a CLI configuration reader with struct-embedded defaults, environment variables and posix compatible flag parsing using the pflag library.

Installation

Install by running:

go get -u github.com/Luzifer/rconfig

OR fetch a specific version:

go get -u gopkg.in/luzifer/rconfig.v2

Run tests by running:

go test -v -race -cover github.com/Luzifer/rconfig

Usage

A very simple usecase is to just configure a struct inside the vars section of your main.go and to parse the commandline flags from the main() function:

package main

import (
  "fmt"
  "github.com/Luzifer/rconfig"
)

var (
  cfg = struct {
    Username string `default:"unknown" flag:"user" description:"Your name"`
    Details  struct {
      Age int `default:"25" flag:"age" env:"age" description:"Your age"`
    }
  }{}
)

func main() {
  rconfig.Parse(&cfg)

  fmt.Printf("Hello %s, happy birthday for your %dth birthday.",
    cfg.Username,
    cfg.Details.Age)
}

Provide variable defaults by using a file

Given you have a file ~/.myapp.yml containing some secrets or usernames (for the example below username is assumed to be "luzifer") as a default configuration for your application you can use this source code to load the defaults from that file using the vardefault tag in your configuration struct.

The order of the directives (lower number = higher precedence):

  1. Flags provided in command line
  2. Environment variables
  3. Variable defaults (vardefault tag in the struct)
  4. default tag in the struct
var cfg = struct {
  Username string `vardefault:"username" flag:"username" description:"Your username"`
}

func main() {
  rconfig.SetVariableDefaults(rconfig.VarDefaultsFromYAMLFile("~/.myapp.yml"))
  rconfig.Parse(&cfg)

  fmt.Printf("Username = %s", cfg.Username)
  // Output: Username = luzifer
}

More info

You can see the full reference documentation of the rconfig package at godoc.org, or through go's standard documentation system by running godoc -http=:6060 and browsing to http://localhost:6060/pkg/github.com/Luzifer/rconfig after installation.

Documentation

Overview

Package rconfig implements a CLI configuration reader with struct-embedded defaults, environment variables and posix compatible flag parsing using the pflag library.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTimeParserFormats

func AddTimeParserFormats(f ...string)

AddTimeParserFormats adds custom formats to parse time.Time fields

func Args added in v1.0.3

func Args() []string

Args returns the non-flag command-line arguments.

func AutoEnv

func AutoEnv(enable bool)

AutoEnv enables or disables automated env variable guessing. If no `env` struct tag was set and AutoEnv is enabled the env variable name is derived from the name of the field: `MyFieldName` will get `MY_FIELD_NAME`

func Parse

func Parse(config interface{}) error

Parse takes the pointer to a struct filled with variables which should be read from ENV, default or flag. The precedence in this is flag > ENV > default. So if a flag is specified on the CLI it will overwrite the ENV and otherwise ENV overwrites the default specified.

For your configuration struct you can use the following struct-tags to control the behavior of rconfig:

default: Set a default value
vardefault: Read the default value from the variable defaults
env: Read the value from this environment variable
flag: Flag to read in format "long,short" (for example "listen,l")
description: A help text for Usage output to guide your users

The format you need to specify those values you can see in the example to this function.

Example
// We're building an example configuration with a sub-struct to be filled
// by the Parse command.
config := struct {
	Username string `default:"unknown" flag:"user,u" description:"Your name"`
	Details  struct {
		Age int `default:"25" flag:"age" description:"Your age"`
	}
}{}

// To have more relieable results we're setting os.Args to a known value.
// In real-life use cases you wouldn't do this but parse the original
// commandline arguments.
os.Args = []string{
	"example",
	"--user=Luzifer",
}

Parse(&config)

fmt.Printf("Hello %s, happy birthday for your %dth birthday.",
	config.Username,
	config.Details.Age)

// You can also show an usage message for your user
Usage()
Output:

Hello Luzifer, happy birthday for your 25th birthday.

func ParseAndValidate added in v1.2.0

func ParseAndValidate(config interface{}) error

ParseAndValidate works exactly like Parse but implements an additional run of the go-validator package on the configuration struct. Therefore additonal struct tags are supported like described in the readme file of the go-validator package:

https://github.com/go-validator/validator/tree/v2#usage

func SetVariableDefaults

func SetVariableDefaults(defaults map[string]string)

SetVariableDefaults presets the parser with a map of default values to be used when specifying the vardefault tag

func Usage

func Usage()

Usage prints a basic usage with the corresponding defaults for the flags to os.Stdout. The defaults are derived from the `default` struct-tag and the ENV.

func VarDefaultsFromYAML

func VarDefaultsFromYAML(in []byte) map[string]string

VarDefaultsFromYAML creates a vardefaults map from YAML raw data

func VarDefaultsFromYAMLFile

func VarDefaultsFromYAMLFile(filename string) map[string]string

VarDefaultsFromYAMLFile reads contents of a file and calls VarDefaultsFromYAML

Types

This section is empty.

Jump to

Keyboard shortcuts

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