summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMitchell Riedstra <mitch@riedstra.dev>2025-04-27 10:22:11 -0400
committerMitchell Riedstra <mitch@riedstra.dev>2025-04-27 10:22:11 -0400
commitc9047cfbc62191ccbe47c2ca0896eb4b192a7223 (patch)
tree2438793104a18dffc9bb49b75802a2d64d2c2bfa
downloadenvflag-c9047cfbc62191ccbe47c2ca0896eb4b192a7223.tar.gz
envflag-c9047cfbc62191ccbe47c2ca0896eb4b192a7223.tar.xz
Initial
-rw-r--r--go.mod3
-rw-r--r--main.go61
2 files changed, 64 insertions, 0 deletions
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..87c20db
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module riedstra.dev/go/envflag
+
+go 1.11.0
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..8c50dc3
--- /dev/null
+++ b/main.go
@@ -0,0 +1,61 @@
+// Package envflag is an extremely small bit of code to make configuration
+// via environment variables a little bit less of a hassle when using
+// the flag package in the standard library.
+package envflag
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "strconv"
+)
+
+// String is a convent way to set value from environment variable,
+// and allow override when a command line flag is set. It's assumed `p` is
+// not nil.
+func String(fl *flag.FlagSet, p *string, name, envvar, usage string) {
+ if v := os.Getenv(envvar); v != "" {
+ *p = v
+ }
+
+ fl.StringVar(p, name, *p, fmt.Sprintf("%s (Environ: '%s')", usage, envvar))
+}
+
+// Bool is a convent way to set value from environment variable,
+// and allow override when a command line flag is set. It's assumed `p` is
+// not nil.
+func Bool(fl *flag.FlagSet, p *bool, name, envvar, usage string) error {
+ if v := os.Getenv(envvar); v != "" {
+ res, err := strconv.ParseBool(v)
+
+ if err != nil {
+ return fmt.Errorf("Bool: cannot parse '%s=%s', %w",
+ envvar, v, err)
+ }
+
+ *p = res
+ }
+
+ fl.BoolVar(p, name, *p, fmt.Sprintf("%s (Environ: '%s')", usage, envvar))
+
+ return nil
+}
+
+// Int is a convent way to set value from environment variable,
+// and allow override when a command line flag is set. It's assumed `p` is
+// not nil.
+func Int(fl *flag.FlagSet, p *int, name, envvar, usage string) error {
+ if v := os.Getenv(envvar); v != "" {
+ res, err := strconv.ParseInt(v, 10, 32)
+ if err != nil {
+ return fmt.Errorf("Int: cannot parse '%s=%s', %w",
+ envvar, v, err)
+ }
+
+ *p = int(res)
+ }
+
+ fl.IntVar(p, name, *p, fmt.Sprintf("%s (Environ: '%s')", usage, envvar))
+
+ return nil
+}