kelseyhightower / envconfig

Golang library for managing configuration data from environment variables
MIT License
5.06k stars 382 forks source link

Struct tag order is important #109

Closed nccurry closed 6 years ago

nccurry commented 6 years ago

I noticed that the order of the struct tags is important and determines whether the split_words functionality words.

I didn't see this mentioned anywhere.

package main

import (
        "os"
        "fmt"
        "github.com/kelseyhightower/envconfig"
)

type backwordTag struct {
        MyBool bool `default:"false",split_words:"true"`
}

type forwardTag struct {
        MyBool bool `split_words:"true",default:"false"`
}

func main() {
        var bt backwordTag
        var ft forwardTag

        os.Setenv("MY_BOOL", "true")

        err := envconfig.Process("", &bt)
        if err != nil {
                fmt.Println("Backword Tag", err)
        }

        fmt.Printf("%t\n", bt.MyBool)

        err = envconfig.Process("", &ft)
        if err != nil {
                fmt.Println("Forward Tag", err)
        }

        fmt.Printf("%t\n", ft.MyBool)
}
[test]$ go run main.go 
false
true
teepark commented 6 years ago

The issue here is syntax. Multiple struct tags are separated by spaces, not commas.

package main

import (
    "fmt"
    "os"

    "github.com/kelseyhightower/envconfig"
)

type backwordTag struct {
    MyBool bool `default:"false" split_words:"true"`
}

type forwardTag struct {
    MyBool bool `split_words:"true" default:"false"`
}

func main() {
    var bt backwordTag
    var ft forwardTag

    os.Setenv("MY_BOOL", "true")

    err := envconfig.Process("", &bt)
    if err != nil {
        fmt.Println("Backword Tag", err)
    }

    fmt.Printf("%t\n", bt.MyBool)

    err = envconfig.Process("", &ft)
    if err != nil {
        fmt.Println("Forward Tag", err)
    }

    fmt.Printf("%t\n", ft.MyBool)
}
true
true
nccurry commented 6 years ago

Ah! Good catch. Thanks