Documentation ¶
Overview ¶
Package env provides a flagr.Parser that is able to read environment variables (and .env files) and set the appropriate flags.
Example ¶
package main import ( "errors" "os" "github.com/flga/flagr" "github.com/flga/flagr/env" ) func main() { var fs flagr.Set _ = flagr.Add(&fs, "flag", flagr.Int(1), "usage") envfile := flagr.Add(&fs, "envfile", flagr.String(".env"), "usage") if err := fs.Parse( os.Args[1:], env.Parse( env.WithPrefix("app"), // prefix every flag with "app" before mapping it env.WithMapper(env.DefaultMapper(",")), // use a custom mapper that treats "," as a separator for all values env.WithStaticDotEnv(".env", true), // tries to read env values from a ".env" file if it exists env.WithDotEnv(envfile, true), // same as above but allows the filename to be dynamic env.WithLookupFunc(os.LookupEnv), // uses the given func to lookup env values (this is a noop, os.LookupEnv is the default) ), ); err != nil { if errors.Is(err, flagr.ErrHelp) { os.Exit(2) } os.Exit(1) } }
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type LookupFunc ¶
LookupFunc returns the value for the given variable and whether it was found.
type Mapper ¶
Mapper maps a flag to the corresponding env var.
func DefaultMapper ¶
DefaultMapper converts flags to env vars by replacing any non alphanumeric character (in the ascii sense) with an underscore.
If splitter is not NoSplit (an empty string), it will be used to try to split env values to lists. If you need to control the splitter per flag, use a custom Mapper.
type Option ¶
type Option func(*options)
func WithDotEnv ¶
WithDotEnv tells the parser to also parse the given .env file. Env vars take precedence over anything defined in it.
Parsing will fail if the file does not exist, unless ignoreMissing is true.
Path will be resolved just in time, so it may be set by other parsers up in the chain.
func WithLookupFunc ¶
func WithLookupFunc(fn LookupFunc) Option
WithLookupFunc replaces the default lookup method (os.LookupEnv) with the given func.
func WithMapper ¶
WithMapper tells the parser how to map flags to env vars and, if the value is expected to be a list, how to split it.
func WithPrefix ¶
WithPrefix prefixes every flag with s before mapping it to the corresponding env var. The prefix need not end in an underscore as one will be added automatically.
func WithStaticDotEnv ¶ added in v0.4.0
WithStaticDotEnv is an alias for WithDotEnv but with a static path.