config

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 2, 2026 License: Apache-2.0 Imports: 15 Imported by: 2

README

Config

Common config library for Internal affairs golang projects

Usage example

This library can be used for load command-line arguments and configuration files.

import (    
    "github.com/relex/gotils/config"
)

type testconf struct {
	Tests []test `mapstructure:"tests"`
}

type test struct {
	Name string `mapstructure:"name"`
	Test string `mapstructure:"test"`
	Foo  string `mapstructure:"foo"`
}

type mordor struct {
	Name      string `mapstructure:"name"`
	Arguments string `mapstructure:"arguments"`
}

var (
	currentIntValue int
	ConfigFile      string
	debug           bool

	conf     = &testconf{}
	mor      = &mordor{}
	function = func(cmd *cobra.Command, args []string) {
		LoadConfig()
		...
	}
)

func init() {
	// add root command: the exe name is automatically detected
	config.AddCmd("", "My service", "This is my long name", function, nil)

	// register manual flags
	config.AddStringFlagToCmd("", &ConfigFile, "config_file", "config.yml", "config file")
	config.AddIntFlagToCmd("", &currentIntValue, "my_value", 3, "This is a test value")
	config.AddBoolFlagToCmd("", &debug, "debug", false, "enable debug level")

	// add parent command
	// config.AddCmd("show", "Show misc info", "", nil, nil)
	config.AddParentCmdWithArgs("show", "Show misc info", &sharedShowFlags, preShowAnything, postShowAnything)

	// register auto flags from struct
	envFlags := struct{
		CheckOS      bool `help:"check OS"`
		CheckNetwork bool
		CheckUser    bool
	} {
		CheckNetwork: true, // default
	}
	// add subcommands by giving full command path, without the program name (root command name)
	config.AddCmdWithArgs("show env", "Show environment information", &envFlags, showEnvInfo)
	config.AddCmdWithArgs("show components", "Show installed components", &compFlags, showComponents)
}

func LoadConfig(file string) {
	ReadConfigFile(file)
	Unmarshal(conf)
    UnmarshalKey("mordor", mor)
    ...
}

// Execute is the initial function to start the program
func Execute() {
	config.Execute()
}

Documentation

Overview

Package config provides standardized configuration parsing and the setup of commands and flags

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddBoolFlagToCmd

func AddBoolFlagToCmd(cmdPath string, v *bool, flag string, defaultValue bool, help string)

AddBoolFlagToCmd adds new bool flag to use with the command-line

func AddBoolPFlagToCmd

func AddBoolPFlagToCmd(cmdPath string, v *bool, flag string, shortflag string, defaultValue bool, help string)

AddBoolPFlagToCmd adds new bool flag and shortflag to use with the command-line

func AddCmd

func AddCmd(use string, short string, long string, run func(args []string), runError func(args []string) error)

AddCmd creates and adds a new command to its parent if it's not the root command

The "use" should contain full command path and usage, for example:

  • "" or "[args]": root command
  • "show [flags...]": first-level command, added to the root command
  • "show account": second-level command, added to the "show" command

All parameters are optional.

func AddCmdWithArgs

func AddCmdWithArgs(use string, short string, flagStruct interface{}, run func(args []string))

AddCmdWithArgs adds a new command with auto flags from given struct (must be pointer)

"flagStruct" must be a pointer to struct - each of the public fields is made a command flag with snake naming style. See AddStructFlagsToCmd for examples.

See AddCmd for the "use" parameter

All parameters are optional.

func AddIntFlagToCmd

func AddIntFlagToCmd(cmdPath string, v *int, flag string, defaultValue int, help string)

AddIntFlagToCmd adds new int flag to use with the command-line

func AddIntPFlagToCmd

func AddIntPFlagToCmd(cmdPath string, v *int, flag string, shortflag string, defaultValue int, help string)

AddIntPFlagToCmd adds new int flag and shortflag to use with the command-line

func AddParentCmdWithArgs

func AddParentCmdWithArgs(use string, short string, flagStruct interface{}, preRun func(), postRun func())

AddParentCmdWithArgs adds a new non-executable parent command with auto flags from given struct (must be pointer)

The "flagStruct" must be a pointer to struct - each of the public fields is made a command flag with snake naming style. See AddStructFlagsToCmd for examples.

See AddCmd for the "use" parameter

All parameters are optional. "preRun" and "postRun" are executed before and after child command's run() respectively

func AddStringFlagToCmd

func AddStringFlagToCmd(cmdPath string, v *string, flag string, defaultValue string, help string)

AddStringFlagToCmd adds new string flag to use with the command-line

func AddStringPFlagToCmd

func AddStringPFlagToCmd(cmdPath string, v *string, flag string, shortflag string, defaultValue string, help string)

AddStringPFlagToCmd adds new string flag and shortflag to use with the command-line

func AddStructFlagsToCmd

func AddStructFlagsToCmd(cmdName string, flagStruct interface{})

AddStructFlagsToCmd adds new struct flags to use with the command-line

flagStruct must be a pointer to struct, for example:

cmdFlags := struct {
	StrIOOpt  string        `help:"Snake named flag"`
	unexposed int
	Secret    []byte        `help:"The Password"`
	Timeout   time.Duration
}{
	StrIOOpt:  "Hey there!",
   Timeout:   5 * time.Second,
}
AddStructFlagsToCmd("test", &cmdFlags)
// Flags:
//   --secret bytesHex     The Password
//   --str_io_opt string   Snake named flag (default "Hey there!")
//   --timeout duration    (default 5s)

Nested structs and embedded structs are also supported, see tests for more examples

func AddStructFlagsToFlags

func AddStructFlagsToFlags(parentLogger logger.Logger, flagSet *pflag.FlagSet, flagStruct interface{})

AddStructFlagsToFlags adds new struct flags to use with the command-line

See AddStructFlagsToCmd for examples

func AddUint16FlagToCmd

func AddUint16FlagToCmd(cmdPath string, v *uint16, flag string, defaultValue uint16, help string)

AddUint16FlagToCmd adds new string flag to use with the command-line

func AddUint16PFlagToCmd

func AddUint16PFlagToCmd(cmdPath string, v *uint16, flag string, shortflag string, defaultValue uint16, help string)

AddUint16PFlagToCmd adds new string flag to use with the command-line

func AddVersionCommand

func AddVersionCommand(version string) string

AddVersionCommand adds -v and --version flags that print version info If version is an empty string or "dev", it will be set to dev-<timestamp>, e.g. dev-2021-05-06T07:48:48Z Returns the version that was set

func Execute

func Execute()

Execute executes the root command

The function finishes the program and DOES NOT return

func GetCmdHelp

func GetCmdHelp(cmdPath string)

GetCmdHelp calls the cmd help for the cmd with the giving name

func GetCmdName

func GetCmdName() string

GetCmdName returns the name of the current executable

func GetVersion

func GetVersion() string

GetVersion returns the configured version number

func ReadConfigFile

func ReadConfigFile(file string)

ReadConfigFile reads the file as the global config and makes that parseable

func SetCommandOutput

func SetCommandOutput(cmdPath string, output string)

SetCommandOutput sets an output to the command that you want

func TryParseConfigFile

func TryParseConfigFile(file string, config interface{}) error

TryParseConfigFile attempts to load the file and unmarshal it to struct of given address

The config arg must be a pointer to struct with mapstructure-tagged fields

The function does not touch the global config or global viper instance

func Unmarshal

func Unmarshal(config interface{})

Unmarshal unmarshals the global config into a Struct.

The config arg must be a pointer to struct with mapstructure-tagged fields

func UnmarshalKey

func UnmarshalKey(key string, config interface{})

UnmarshalKey takes a single key from the global config and unmarshals it into a Struct.

The config arg must be a pointer to struct with mapstructure-tagged fields

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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