From 9e258fdd9e231e2df02ccb3394572e7bf6454554 Mon Sep 17 00:00:00 2001 From: bemasher Date: Sun, 18 Sep 2016 03:59:53 -0600 Subject: [PATCH] Allow overriding flag defaults with environment variables. Thanks to kwd42 for this feature suggestion. --- README.md | 18 ++++++++++++++++++ flags.go | 18 +++++++++++++++++- main.go | 1 + 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 363ec69de..795ed379e 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,24 @@ rtltcp specific: -tunerxtalfreq=0: set tuner xtal frequency ``` +Flag default values may be overridden via environment variables which are a flag's name in all-caps prefixed by `RTLAMR_`. Flags passed at time of execution will override any values set by environment variable. + +```bash +rtlamr -h + +... + -msgtype=scm: message type to receive: scm, scm+, idm, r900 and r900bcd +... +``` + +```bash +RTLAMR_MSGTYPE=idm rtlamr -h + +... + -msgtype=idm: message type to receive: scm, scm+, idm, r900 and r900bcd +... +``` + Running the receiver is as simple as starting an `rtl_tcp` instance and then starting the receiver: ```bash diff --git a/flags.go b/flags.go index df5dcfe32..33e85cc0e 100644 --- a/flags.go +++ b/flags.go @@ -92,7 +92,7 @@ func RegisterFlags() { } format := " -%s=%s: %s\n" - fmt.Fprintf(os.Stderr, format, f.Name, f.DefValue, f.Usage) + fmt.Fprintf(os.Stderr, format, f.Name, f.Value, f.Usage) }) } @@ -106,6 +106,22 @@ func RegisterFlags() { } } +func EnvOverride() { + flag.VisitAll(func(f *flag.Flag) { + envName := "RTLAMR_" + strings.ToUpper(f.Name) + flagValue := os.Getenv(envName) + if flagValue != "" { + log.Printf("Environment variable %q overrides flag %q with %q\n", envName, f.Name, flagValue) + if err := flag.Set(f.Name, flagValue); err != nil { + log.Fatalf( + "Environment variable %q failed to override flag %q with value %q: %q\n", + envName, f.Name, flagValue, err, + ) + } + } + }) +} + func HandleFlags() { var err error diff --git a/main.go b/main.go index f46c7992b..d76c1c47d 100644 --- a/main.go +++ b/main.go @@ -213,6 +213,7 @@ var ( func main() { rcvr.RegisterFlags() RegisterFlags() + EnvOverride() flag.Parse() if *version {