spf13 / viper

Go configuration with fangs
MIT License
27.38k stars 2.02k forks source link

Allow custom EnvKeyReplacer from "_" to other #1655

Open honmaple opened 1 year ago

honmaple commented 1 year ago

Preflight Checklist

Problem Description

When some config include _, and I read it from environment variables,I will change _ to other string, such as __

cf := viper.New()
cf.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "_", "__"))
cf.SetEnvPrefix("app")
cf.BindEnv("server.mode")
cf.BindEnv("server.listen_port")

fmt.Println(cf.Get("server.listen_port"))

But after set envPrefix, if I want to set server.listen_port, I must use APP__LISTEN__PORT rather than APP_LISTEN__PORT

Proposed Solution

envPrefix + _ would not affect envKeyReplacer, so I can set vars by

APP_SERVER_MODE=dev
APP_SERVER_LISTEN__PORT=8000

Not

APP__SERVER_MODE=dev
APP__SERVER_LISTEN__PORT=8000

Alternatives Considered

For quick fixed, change getEnv function

func (v *Viper) getEnv(key string) (string, bool) {
    if v.envKeyReplacer != nil {
        if v.envPrefix != "" {
            key = strings.TrimPrefix(key, v.mergeWithEnvPrefix(""))
            key = v.envKeyReplacer.Replace(key)
            key = v.mergeWithEnvPrefix(key)
        } else {
            key = v.envKeyReplacer.Replace(key)
        }
    }

    val, ok := os.LookupEnv(key)

    return val, ok && (v.allowEmptyEnv || val != "")
}

Additional Information

No response

github-actions[bot] commented 1 year ago

šŸ‘‹ Thanks for reporting!

A maintainer will take a look at your issue shortly. šŸ‘€

In the meantime: We are working on Viper v2 and we would love to hear your thoughts about what you like or don't like about Viper, so we can improve or fix those issues.

ā° If you have a couple minutes, please take some time and share your thoughts: https://forms.gle/R6faU74qPRPAzchZ9

šŸ“£ If you've already given us your feedback, you can still help by spreading the news, either by sharing the above link or telling people about this on Twitter:

https://twitter.com/sagikazarmark/status/1306904078967074816

Thank you! ā¤ļø