Skip to content

First Class Environment Variable Binding #104

@integrii

Description

@integrii

Flaggy currently works alongside the default environment binding that comes in the standard library. For example:

var := os.Getenv("MY_VAR") // set the var from the environment values MY_VAR
flaggy.String(&var, "v", "variable", "Just some variable") // Tell flaggy to overwrite the `var` if the `-v` or `--variable` flags are passed.
flaggy.Parse()

However, this gets a lot worse if your environment variable string needs to ultimately get parsed into another type:

durationStr := os.Getenv("DELAY_SECONDS") // set a time.Duration ultimately
duration, err := time.ParseDuration(durationStr)
if err != nil {
    panic("bad duration")
}
flaggy.Duration(&duration, "d", "duration" "Just some duration") // Tell flaggy to overwrite the duration if this flag is used and a duration is passed
flaggy.Parse()

That's a lot more code. Now, if you mixed in loading from configs as a baseline before parsing env vars, things start to get pretty messy.

So, it might be nice if flaggy could extend it's existing ability to parse a string into many different types to incoming environment variables. A simple set of .BindEnv() functions could do the trick:

var duration time.Duration
flaggy.DurationEnv(&duration, "DELAY_SECONDS")
flaggy.Duration(&duration, "d", "duration" "Just some duration") // Tell flaggy to overwrite the duration if this flag is used and a duration is passed
flaggy.Parse()

Alternatively, it could be possible to determine the type by the pointer to the target variable.

var duration time.Duration
flaggy.Env(&duration, "DELAY_SECONDS")
flaggy.Duration(&duration, "d", "duration" "Just some duration") // Tell flaggy to overwrite the duration if this flag is used and a duration is passed
flaggy.Parse()

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalProposed changes to flaggy

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions