Skip to content

Commit

Permalink
Support SnakeCase style environment name
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Dec 22, 2016
1 parent afba9d6 commit 636f81b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
20 changes: 13 additions & 7 deletions configor.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,20 +113,26 @@ func processTags(config interface{}, prefix ...string) error {

configType := configValue.Type()
for i := 0; i < configType.NumField(); i++ {
fieldStruct := configType.Field(i)
field := configValue.Field(i)
var (
envNames []string
fieldStruct = configType.Field(i)
field = configValue.Field(i)
envName = fieldStruct.Tag.Get("env") // read configuration from shell env
)

// read configuration from shell env
var envName = fieldStruct.Tag.Get("env")
if envName == "" {
envName = strings.ToUpper(strings.Join(append(prefix, fieldStruct.Name), "_"))
envNames = append(envNames, strings.Join(append(prefix, fieldStruct.Name), "_"))
envNames = append(envNames, strings.ToUpper(strings.Join(append(prefix, fieldStruct.Name), "_")))
} else {
envNames = []string{envName}
}

if envName != "" {
if value := os.Getenv(envName); value != "" {
for _, env := range envNames {
if value := os.Getenv(env); value != "" {
if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil {
return err
}
break
}
}

Expand Down
29 changes: 28 additions & 1 deletion configor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (

"gopkg.in/yaml.v2"

"github.com/jinzhu/configor"
"github.com/BurntSushi/toml"
"github.com/jinzhu/configor"
)

type Anonymous struct {
Expand Down Expand Up @@ -274,6 +274,33 @@ func TestResetPrefixToBlank(t *testing.T) {
}
}

func TestResetPrefixToBlank2(t *testing.T) {
config := generateDefaultConfig()

if bytes, err := json.Marshal(config); err == nil {
if file, err := ioutil.TempFile("/tmp", "configor"); err == nil {
defer file.Close()
defer os.Remove(file.Name())
file.Write(bytes)
var result Config
os.Setenv("CONFIGOR_ENV_PREFIX", "-")
os.Setenv("APPName", "config2")
os.Setenv("DB_Name", "db_name")
defer os.Setenv("CONFIGOR_ENV_PREFIX", "")
defer os.Setenv("APPName", "")
defer os.Setenv("DB_Name", "")
configor.Load(&result, file.Name())

var defaultConfig = generateDefaultConfig()
defaultConfig.APPName = "config2"
defaultConfig.DB.Name = "db_name"
if !reflect.DeepEqual(result, defaultConfig) {
t.Errorf("result should equal to original configuration")
}
}
}
}

func TestReadFromEnvironmentWithSpecifiedEnvName(t *testing.T) {
config := generateDefaultConfig()

Expand Down

0 comments on commit 636f81b

Please sign in to comment.