-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
59 lines (51 loc) · 1.45 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package app
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"os"
"strings"
)
var (
Command = &cobra.Command{
Use: "grpc-rpf",
Short: "GRPC Remote Port Forward",
PersistentPreRunE: BindEnv("GRPC_RPF"),
}
DevMode = false
)
func init() {
Command.PersistentFlags().BoolVar(&DevMode, "dev-mode", false, "run in development mode. increases output verbosity.")
}
func HandleErrorWithExitCode(function func() error, code int) {
if err := function(); err != nil {
if DevMode {
fmt.Printf("%+v", err)
} else {
fmt.Printf("%v", err)
}
os.Exit(code)
}
}
func BindEnv(envPrefix string) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
v := viper.New()
v.SetEnvPrefix(envPrefix)
v.AutomaticEnv()
cmd.Flags().VisitAll(func(f *pflag.Flag) {
// Environment variables can't have dashes in them, so bind them to their equivalent
// keys with underscores, e.g. --favorite-color to FAVORITE_COLOR
if strings.Contains(f.Name, "-") {
envVarSuffix := strings.ToUpper(strings.ReplaceAll(f.Name, "-", "_"))
_ = v.BindEnv(f.Name, fmt.Sprintf("%s_%s", envPrefix, envVarSuffix))
}
// Apply the viper config value to the flag when the flag is not set and viper has a value
if !f.Changed && v.IsSet(f.Name) {
val := v.Get(f.Name)
_ = cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val))
}
})
return nil
}
}