Created
November 1, 2024 08:55
-
-
Save gjreasoner/75fb7956e0d804986b44ae3c6d4f9507 to your computer and use it in GitHub Desktop.
Nested viper and unmarshal into config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
viper "github.com/spf13/viper" | |
) | |
type Config struct { | |
Stripe Stripe | |
TestKey string | |
DefaultKey string `mapstructure:"default_key"` | |
} | |
type Stripe struct { | |
SecretKey string `mapstructure:"secret_key"` | |
} | |
func main() { | |
viper.SetConfigName("config") | |
viper.SetConfigType("yaml") | |
viper.AddConfigPath(".") | |
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) | |
viper.AutomaticEnv() | |
_ = viper.ReadInConfig() | |
viper.BindEnv("DEFAULT_KEY"); | |
viper.BindEnv("STRIPE.SECRET_KEY"); | |
var config Config | |
_ = viper.Unmarshal(&config) | |
fmt.Println("stripe key:",config.Stripe.SecretKey) | |
fmt.Println("default key:",config.DefaultKey) | |
} | |
// $ STRIPE_SECRET_KEY=test DEFAULT_KEY=123 go run . | |
// stripe key: test | |
// default key: 123 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment