README

act

Microservices oriented 12-factor Go library for parsing environment variables and command line flags to arbitrary config struct using struct tags to define default values and to override flag names and environment variables' names.

Build Status Go Coverage Go Reference Go Report License

This package in intended to be used to parse command line arguments and environment variables into an arbitrary config struct. This struct may contain multiple nested structs, they all will be processed recursively. Names of the flags and environment variables are automatically generated. Flags will be kebab case of the field name eventually preceded by parent fields in case of nested structs. Names of environment variables will be similar, but additionally prefixed with command name and then snake and upper cased. Description of each flag will also be automatically generated in a human friendly way as much as possible. Additionally, you may override these auto-generated names using the struct tags and you also may define default value.

  • flag - override generated flag name
  • env - override generated environment variable name
  • help - override generated flag description
  • def - override default (zero) value

Important: all struct fields should be exported.

Custom flag types

Besides the types supported by flag package, this package provides additional types:

  • act.StringSlice - doesn't support multiple flags but instead supports comma separated strings, i.e. "foo,bar"
  • act.IntSlice - doesn't support multiple flags but instead supports comma separated integers, i.e. "5,-8,0"
  • act.URL

Order of precedence:

  • command line options
  • environment variables
  • default values

Examples

Run make test-verbose to see examples output.

Subcommands

These are handled just like by standard library's flag package.

package main

import (
	"log"
	"os"

	"go.ectobit.com/act"
)

func main() {
	subCmd := os.Args[1]
	switch subCmd {
	case "create":
		config := &struct{}{}
		createCmd := act.New("create")

		if err := createCmd.Parse(config, os.Args[2:]); err != nil {
			log.Println(err)
		}

		// Implementation

	case "delete":
		config := &struct{}{}
		deleteCmd := act.New("create")

		if err := deleteCmd.Parse(config, os.Args[2:]); err != nil {
			log.Println(err)
		}

		// Implementation
	}
}

TODO

  • support req struct tag to mark required values
Expand ▾ Collapse ▴

Documentation

Overview

    Package act is a library for parsing command line flags, environment variables and default values defined by struct tag "def" respecting the order of precedence according to the 12-factor principles. It generates predefined flag names and environment variables names by the fields path of the supplied config, but allows this to be overridden by struct tags "flag" and "env".

    Example (Advanced)
    Output:
    
    
    Example (Basic)
    Output:
    
    

    Index

    Examples

    Constants

    This section is empty.

    Variables

    View Source
    var (
    	ErrInvalidConfigType = errors.New("invalid config type")
    	ErrUnsupportedType   = errors.New("type not supported")
    )

      Errors.

      Functions

      This section is empty.

      Types

      type Act

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

        Act is an abstraction of a CLI command.

        func New

        func New(name string, opts ...Option) *Act

          New creates new act command.

          func (*Act) Parse

          func (a *Act) Parse(config interface{}, flags []string) error

            Parse parses command line flags, environment variables and default values. It populates supplied pointer to configuration struct with values according to the order of precedence.

            type IntSlice

            type IntSlice []int

              IntSlice implements flag.Getter interface for []int type.

              func (*IntSlice) Get

              func (f *IntSlice) Get() interface{}

                Get returns flag's value.

                func (*IntSlice) Set

                func (f *IntSlice) Set(s string) error

                  Set sets flag's value by splitting provided comma separated string.

                  func (*IntSlice) String

                  func (f *IntSlice) String() string

                    String formats flag's value.

                    type Option

                    type Option func(a *Act)

                      Option defines optional parameters to the constructor.

                      func WithErrorHandling

                      func WithErrorHandling(errorHandling flag.ErrorHandling) Option

                        WithErrorHandling is an option to change error handling similar to flag package.

                        func WithLookupEnvFunc

                        func WithLookupEnvFunc(fn func(string) (string, bool)) Option

                          WithLookupEnvFunc may be used to override default os.LookupEnv function to read environment variables values.

                          func WithOutput

                          func WithOutput(w io.Writer) Option

                            WithOutput is an option to change the output writer similar as flag.SetOutput does.

                            func WithUsage

                            func WithUsage(parentCmdName string) Option

                              WithUsage allows to prefix your command name with a parent command name.

                              type StringSlice

                              type StringSlice []string

                                StringSlice implements flag.Getter interface for []string type.

                                func (*StringSlice) Get

                                func (f *StringSlice) Get() interface{}

                                  Get returns flag's value.

                                  func (*StringSlice) Set

                                  func (f *StringSlice) Set(s string) error

                                    Set sets flag's value by splitting provided comma separated string.

                                    func (*StringSlice) String

                                    func (f *StringSlice) String() string

                                      String formats flag's value.

                                      type URL

                                      type URL struct {
                                      	*url.URL
                                      }

                                        URL implements flag.Getter interface for url.URL type.

                                        func (*URL) Get

                                        func (f *URL) Get() interface{}

                                          Get returns flag's value.

                                          func (*URL) Set

                                          func (f *URL) Set(s string) error

                                            Set sets flag's value by parsing provided url.

                                            func (*URL) String

                                            func (f *URL) String() string

                                              String formats flag's value.

                                              Source Files