Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Márk Sági-Kazár
    @sagikazarmark
    You can set a key name replacer and replace dots with underscores
    Then you can use MYPREFIX_LEVEL1_LEVEL2
    Abdelkader Bouadjadja
    @medinae
    Not arrays sorry, but i meant nested configs with multiple levels.
    Excellent, thanks a lot.
    Rishi
    @rishirajgarg_twitter
    Hi .. I have recently started working on cobra, can someone help me to know how to read a custom yml from cobra command line using viper.
    Itshardtopickanusername
    @Itshardtopickanusername
    How do you guys share one viper instance to the multiple packages?
    Darragh Bailey
    @electrofelix
    When using viper.AutomaticEnv() is there a way to get env variable to display in the help along with each option automatically?
    Darragh Bailey
    @electrofelix
    I've used the following code to handle this, but seems like something that would be nice to enable automatically:
        RootCmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {
            envKey := strings.ToUpper(replacer.Replace(f.Name))
            f.Usage = fmt.Sprintf("%s [env: %s]", f.Usage, envKey)
        })
    Luke Hinds
    @lukehinds
    Which viper.Get method should I use to retrieve JSON from a YAML config?
    jim
    @tjimsk
    is it supported to use relative path in viper.AddConfigPath() ?
    Dan Rollo
    @bhamail
    Hi. I found myself in a rabbit hole, and put together a PR that I hope will help others avoid the issue. spf13/viper#949
    Is this the right forum to post about this? Thanks for a great tool BTW!
    Juan Ignacio Borda
    @juanitomint

    Hi Vipers!!!
    Im reading an INI file and I want to extract the sections names
    ie:

    [section 1]
    param1=foo1
    param2=bar1
    
    [section2]
    param1=foo2
    param2=bar2
    
    ......
    .......

    is this possible with viper!?

    Juan Ignacio Borda
    @juanitomint
    I need to get a map like ["section1","section2" ....]

    Which viper.Get method should I use to retrieve JSON from a YAML config?

    did you tried with viper.GetString("path.to.your.json") ?
    then parse with viper again

    Juan Ignacio Borda
    @juanitomint

    Hi Vipers!!!
    Im reading an INI file and I want to extract the sections names
    ie:

    [section 1]
    param1=foo1
    param2=bar1
    
    [section2]
    param1=foo2
    param2=bar2
    
    ......
    .......

    is this possible with viper!?

    dont worry i've already done this with a regular expresion and a file read

    Marques Johansson
    @displague
    I asked a similar question in Slack, and @sagikazarmark created an FAQ tracking issue: spf13/viper#969
    Cong Luwen
    @congve1
    Hi guys, the signature of the MergeConfigMap will return an "error", but when I'm looked into the source code, I found that this method just return a nil error. Is there a way to make it return an error when the merge procedure is wrong?
    Márk Sági-Kazár
    @sagikazarmark
    Hey folks!
    Viper is heading towards v2 and needs your input. Please give us your thoughts and feedback: https://forms.gle/f96kZQuBcuxW2p5E8
    Thanks!
    Márk Sági-Kazár
    @sagikazarmark
    Christian Francia
    @ctfrancia

    Hey guys, really small question here but in the README of viper, I don't see any documentation as to how to write to the the config file. I understand that there is the viper.WriteConfig() but what I am wishing to do is something like:

    viper.WriteConfig("key.key", "val")

    is there a semantic approach to staging changes to the config file before viper.WriteConfig() ?

    John Millner
    @johnmillner
    Hey all - i created this issue before noticing this IRC - got a small trouble shooting that would be great to have some help on - trying to get the envVar overrides to be in all underscores rather than periods - am i missing something obvious? spf13/viper#1029
    booshlinux
    @booshlinux

    Hello all, Quick question. When invoking

    viper.GetString("xyz")

    is there an automatic conversion from string to bool when the string in the yaml file is set to "no"?
    I'm seeing this behavior, and I'm not sure if that is configurable.

    Omer Hamerman
    @omerxx

    Hello friends! I'm working with environment variables to set configurations in place and it seems that viper.IsSet() is not picking them up, my config is:

    accounts:
      someaccount: "one"

    When I set this structure from and environment variable like so: ACCOUNTS_SOMEACCOUNT=one (without reconfiguring this from the config.yaml file), while viper.GetString(accounts.someaccount) works as expected, viper.IsSet('accounts') does not. When setting the structure through yaml as the example above everything works as expected.
    Am I missing something? Is this a bug or intentional behavior? Any tips on how to overcome this?

    Mark Petrovic
    @ae6rt
    What is the recommended or reasonable pattern to use for a viper.GetX(key) when the value at rest in the config file is, say, a hex string, but you really want the Get to return the hex-decoded byte slice? Maybe this is an antipattern, but thought I'd ask.
    1 reply
    Muhammet Ali AKBAY
    @muhammetaliakbay
    Hi people, is it possible to use environment variables in yaml configuration file eg: "${VARIABLE}" ?
    recio
    @recio:matrix.org
    [m]
    hello there! i think i'm missing some documentation on how to declare noop flags (like --version, which displays the version when set). Do I need to use this kind of flag as a boolean flag or is there another method? Thanks in advance!
    nvm, i found it 😅
    linuxbsdfreak
    @linuxbsdfreak

    How do i parse the following yaml with viper ?

    dbInstance:
      name: pg-instance
      id: test-db
      storageGB: 5
      dbInstanceClass: db.t2.small
      multiAZ: true
      publiclyAccessible: false
      engineVersion: "9.6"
      storageType: gp2
      region: eu-central-1
      whiteList:
        - 127.0.0.1
        - 127.0.0.2
      clothing:
         jacket: leather
         trousers: denim

    I am parsing as follows

    // Configurations exported
    type Configurations struct {
            DBInstance                                DBInstanceConfigurations
    }
    type DBInstanceConfigurations struct {
            Name                string
            Id                  string
            StorageGB               string
            DBInstanceClass     string
            EngineVersion       string
            StorageType         string
            Region                          string
            MultiAZ                     bool
            PubliclyAccessible  bool
            whiteList           string `mapstructure:"path_map"`
    }
    func main() {
            viper.SetConfigName("config")
            // Set the path to look for the configurations file
            viper.AddConfigPath(".")
            // Enable VIPER to read Environment Variables
            viper.AutomaticEnv()
            viper.SetConfigType("yaml")
            var configuration Configurations
            if err := viper.ReadInConfig(); err != nil {
                    fmt.Printf("Error reading config file, %s", err)
            }
            err := viper.Unmarshal(&configuration)
            if err != nil {
                    fmt.Printf("Unable to decode into struct, %v", err)
            }
    
            fmt.Println("DBInstanceName is\t", configuration.DBInstance.Name)
            fmt.Println("DBInstanceID is\t", configuration.DBInstance.Id)
            fmt.Println("Storage is\t", configuration.DBInstance.StorageGB)
            fmt.Println("DBInstanceClass is\t", configuration.DBInstance.DBInstanceClass)
            fmt.Println("EngineVersion is\t", configuration.DBInstance.EngineVersion)
            fmt.Println("MultiAZ is\t", configuration.DBInstance.MultiAZ)
            fmt.Println("PubliclyAccessible is\t", configuration.DBInstance.PubliclyAccessible)
            fmt.Println("StorageType is\t", configuration.DBInstance.StorageType)
            fmt.Println("Region is\t", configuration.DBInstance.Region)
            fmt.Println("Whitelist is\t", configuration.DBInstance.whiteList)
    }

    I would like to parse that whiteList IPs for looping and also the clothing key with the struct way ?

    linuxbsdfreak
    @linuxbsdfreak
    Any suggestions ?
    linuxbsdfreak
    @linuxbsdfreak
    Any examples on how i can do it with structs ?
    Siddhant N Trivedi
    @sidntrivedi012
    Hey all, when we use a watchConfig() on a certain directory containing the secrets file, do we need to read the config again whenever a onConfigChange() event is created? or viper reads it automatically?
    Siddhant N Trivedi
    @sidntrivedi012
    Also, viper doesn't seem to watch changes in config present in any other directory other than the home directory of the project (.) . Is it intentional or I am doing something wrong?
    Jan Christoph Uhde
    @ObiWahn
    Hi, how do I get viper itself more verbose?
    Unfortunately when googling for it I mostly find people that what to increase the log level of their application.
    Jan Christoph Uhde
    @ObiWahn
    Jan Christoph Uhde
    @ObiWahn
    How do I merge 2 remote vipers that live in consul in keys config/a & config/b
    pradeepkusingh
    @pradeepkusingh
    How to read config files residing in github?
    Sam Pointer
    @sampointer

    With a configuration file like:

    command1:
      foo: value
      bar: value

    and using Cobra and Viper together I understand how to access the nested keys viper.GetString("command1.foo"). What I cannot understand is how to bind flags of a subcommand correctly. Both of:

    viper.BindPFlag("command1.foo", command1Cmd.Flags().Lookup("foo"))
    viper.Sub("command1").BindPFlag("foo", command1Cmd.Flags().Lookup("foo"))

    produce a segment violation. I am sure there must be a way to bind into a nested structure but I cannot understand how. This seems like a fairly common thing one would want to do with a Cobra program consisting of many subcommands but I cannot find any prior art. Any help appreciated.

    Jan Christoph Uhde
    @ObiWahn
    @sagikazarmark could you provide a bit guidance?
    Márk Sági-Kazár
    @sagikazarmark
    Unfortunately there is no such thing built into Viper and there shouldn't be! IMHO Cobra should provide a better integration for Viper, not the other way around.
    Jan Christoph Uhde
    @ObiWahn
    @sagikazarmark: https://0x0.st/-BRc.go that is what I have tried. This home brew "viper config module" is not created by me and is used in several binaries. So I can not easily remove or change everything. I have tried to extend it by adding the merge of the second viper.
            if merge {
                fmt.Fprintf(os.Stderr, "merge config \n")
                // get remote provider
                // provider was ok, now we use our own!
                provider := tipsterRemoteProvider{
                    provider: remoteProviderName,
                    endpoint: consulEndpoint,
                    path: key,
                }
    
                fmt.Fprintf(os.Stderr, "trying to read viper from remote provider: %+v \n", provider)
    
                ioReader, err := realViper.RemoteConfig.Get(provider)
                if err != nil {
                    fmt.Printf("Can't get remote config from consul: %s\n", err)
                    os.Exit(1)
                }
                err = viper.MergeConfig(ioReader)
    I think this is the interesting part.
    where viper is a viper and realViper is github.com/spf13/viper
    Jan Christoph Uhde
    @ObiWahn
    Disclaimer: I am not a go expert but I am tasked with reviving the project, after the company split and hired new people (including me) I have more of a C++ background.
    Jan Christoph Uhde
    @ObiWahn
    func init() {
        cobra.OnInitialize(func() {
            config_viper.Setup(config.ServiceName, config.File, config.ConfigFileType, config.ConsulEndpoint)
    
            subKey := "risk.userbeteventrisk.limits"
            err := config_viper.SetupSubViper(subKey, config.ServiceName+"_limits", config.LimitsFile, config.ConfigFileType, config.ConsulEndpoint)
            if err != nil {
                log.Fatal().Err(err).Msg("could not configure limits")
            }
            config.Config = config.Load(viper.GetViper())
            logging.Setup(config.Config.Logging)
        })
    
        rootCmd.PersistentFlags().StringVar(&config.File, "config", "", "config file")
        rootCmd.PersistentFlags().StringVar(&config.LimitsFile, "config-limits", "", "config file for limits")
        rootCmd.PersistentFlags().StringVar(&config.ConsulEndpoint, "consul", "", "consul endpoint")
    }
    This is probably the other interesting snippet.
    Peter Bocan
    @PeterBocan
    Hey guys, can we get some attention to this life improvement thing at some point? It would be fantastic if there was a stricter Unmarshalling option. spf13/viper#675
    Dmitry Kireev
    @AutomationD
    Hey all, how's going? I'm wondering if there is any good recipe for implementing terraform-like variables rendering with viper? Should I build an abstracton on top of it, or there is something already that would allow us to render${var.variable_name}?
    Dmitry Kireev
    @AutomationD
    It seems like I should be going mapstructure path
    Ingo Bürk
    @Airblader
    Hi everyone! Is there a reverse of viper.Unmarshal, i.e. a way to encode my own struct back into config? I want to do this so that I can write the config through viper again. Currently the only option I see is using mapstructure myself to decode it to a key-val map, ranging over that to set each key-val individually and then writing the file with viper. But that's quite manual + I do not have access to the decoder config in viper.