Skip to content

Commit

Permalink
Allow overriding flag defaults with environment variables.
Browse files Browse the repository at this point in the history
Thanks to kwd42 for this feature suggestion.
  • Loading branch information
bemasher committed Sep 18, 2016
1 parent a0ec0e8 commit 9e258fd
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 17 additions & 1 deletion flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}

Expand All @@ -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

Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ var (
func main() {
rcvr.RegisterFlags()
RegisterFlags()
EnvOverride()

flag.Parse()
if *version {
Expand Down

0 comments on commit 9e258fd

Please sign in to comment.