-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Closed as not planned
Labels
Description
Hello everyone,
I hope there is no duplicate for that.
I'm new to Golang therefore to viper. My use case is to have a structure as a default value, that can be overridden via an other way (env variable, ...). I want to avoid using SetDefault since it could be a lot of config variable in nested configuration.
I managed to to that by marshaling my structure with JSON and than passing the byte slice into ReadConfig .
package main
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"github.com/spf13/viper"
)
// Config : Application configuration
type Config struct {
Jwt JwtConfig
}
// JwtConfig : JWT configuration
type JwtConfig struct {
Secret string
}
func main() {
cfg := Config{
Jwt: JwtConfig{
Secret: "helicopter",
},
}
viper.SetConfigType("json")
cfgJSON, err := json.Marshal(cfg)
if err != nil {
panic(err)
}
viper.ReadConfig((bytes.NewBuffer(cfgJSON)))
viper.SetEnvPrefix("TEST")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
fmt.Println(viper.Get("jwt.secret"))
}My question is : is it the prefered way to do it ? Or maybe is there a more efficient way to do that without JSON/YAML marshalling ?
Best,
Matthieu.
luanguimaraesla, ThinCats, sebnyberg, howdoicomputer, tico8 and 15 more