Skip to content

Default values doesn't work (SetDefault function) #158

Closed
@vlkv

Description

Hi! I'm trying to use default values for my configuration params. They seem to be NOT working. Here is the example:

package main
import (
    "fmt"
    "github.com/spf13/viper"
)

func main() {
    c := viper.New()
    c.SetConfigFile("./config.json")
    c.SetConfigType("json")
    err := c.ReadInConfig()
    if err != nil {
        fmt.Errorf("Error %v\n", err)
    }

    //c.SetTypeByDefaultValue(false)
    c.SetDefault("params.p2", "TWO")
    c.SetDefault("params.p3", "333")

    fmt.Println(c.Get("params.p1"))
    fmt.Println(c.Get("params.p2"))
    fmt.Println(c.Get("params.p3"))
    fmt.Println(c.Get("params.p4"))

    /* Output:
    one   - correct
    two   - correct
    <nil> - WRONG! Expected 333
    <nil> - correct
    */
}

And the config.json is

{
    "params": {
        "p1": "one",
        "p2": "two"
    }
}

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions