configstruct

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2020 License: MIT Imports: 6 Imported by: 31

README

configstruct

Simple Go module to parse a configuration from environment and cli flags using struct tags.

Usage

// define a struct with tags for env name, cli flag and usage
type Config struct {
	Hostname string `env:"CONFIGSTRUCT_HOSTNAME" cli:"hostname" usage:"hostname value"`
	Port     int    `env:"CONFIGSTRUCT_PORT" cli:"port" usage:"listen port"`
	Debug    bool   `env:"CONFIGSTRUCT_DEBUG" cli:"debug" usage:"debug mode"`
}

// create a variable of the struct type and define defaults if needed
conf := testConfig{
    Hostname: "localhost",
    Port:     8000,
    Debug:    true,
}

// now parse values from first env and then cli into this var
err := configstruct.Parse(&conf)
if err != nil {...}

// if you prefer ENV with precedence over cli than use option
err := configstruct.Parse(&conf, configstruct.WithPrecedenceEnv())
if err != nil {...}

Documentation

Overview

Package configstruct provides a parse function to fill a config struct with values from cli flags or environment

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(c interface{}, opts ...Option) error

Parse uses a given struct c with tags and parses values from env or cli flags, it uses the default FlagSet and os.Args

Example

Example for using `configstruct` with default values.

// define a struct with tags
type Config struct {
	Hostname string `env:"CONFIGSTRUCT_HOSTNAME" cli:"hostname" usage:"hostname value"`
	Port     int    `env:"CONFIGSTRUCT_PORT" cli:"port" usage:"listen port"`
	Debug    bool   `env:"CONFIGSTRUCT_DEBUG" cli:"debug" usage:"debug mode"`
}

// create a variable of the struct type and define defaults if needed
conf := testConfig{
	Hostname: "localhost",
	Port:     8000,
	Debug:    true,
}

// now parse values from first cli flags and then env into this var
err := Parse(&conf)
if err != nil {
	fmt.Printf("can't parse config %s", err)
}

func ParseWithFlagSet added in v1.1.0

func ParseWithFlagSet(flagSet *flag.FlagSet, cliArgs []string, c interface{}, opts ...Option) error

ParseWithFlagSet can use a specific FlagSet and args slice to parse data from

Types

type Option added in v1.2.0

type Option func(c *config)

Options is an config setting function

func WithPrecedenceCli added in v1.2.0

func WithPrecedenceCli() Option

WithPrecedenceCli enabled precedence of cli over ENV values (default)

func WithPrecedenceEnv added in v1.2.0

func WithPrecedenceEnv() Option

WithPrecedenceEnv enabled precedence of ENV values over cli

Jump to

Keyboard shortcuts

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