如果环境变量为空,如何分配默认值?

huangapple go评论117阅读模式
英文:

How to assign default value if env var is empty?

问题

如果在Go语言中环境变量未设置,你如何分配默认值?

在Python中,我可以这样做:mongo_password = os.getenv('MONGO_PASS', 'pass'),其中pass是当MONGO_PASS环境变量未设置时的默认值。

我尝试了基于os.Getenv为空的if语句,但由于变量赋值的作用域问题,这似乎不起作用。而且我正在检查多个环境变量,所以我不能在if语句内部处理这些信息。

英文:

How do you assign a default value if an environment variable isn't set in Go?

In Python I could do mongo_password = os.getenv('MONGO_PASS', 'pass') where pass is the default value if MONGO_PASS env var isn't set.

I tried an if statement based on os.Getenv being empty, but that doesn't seem to work due to the scope of variable assignment within an if statement. And I'm checking for multiple env var's, so I can't act on this information within the if statement.

答案1

得分: 177

没有内置的方法可以回退到默认值,所以你需要使用传统的 if-else 来处理。

但是你可以创建一个辅助函数来简化操作:

  1. func getenv(key, fallback string) string {
  2. value := os.Getenv(key)
  3. if len(value) == 0 {
  4. return fallback
  5. }
  6. return value
  7. }

需要注意的是,正如 @michael-hausenblas 在评论中指出的那样,如果环境变量的值真的为空,你将得到回退值。

正如 @ŁukaszWojciechowski 指出的,更好的方法是使用 os.LookupEnv

  1. func getEnv(key, fallback string) string {
  2. if value, ok := os.LookupEnv(key); ok {
  3. return value
  4. }
  5. return fallback
  6. }
英文:

There's no built-in to fall back to a default value,
so you have to do a good old-fashioned if-else.

But you can always create a helper function to make that easier:

  1. func getenv(key, fallback string) string {
  2. value := os.Getenv(key)
  3. if len(value) == 0 {
  4. return fallback
  5. }
  6. return value
  7. }

Note that as @michael-hausenblas pointed out in a comment,
keep in mind that if the value of the environment variable is really empty, you will get the fallback value instead.

Even better as @ŁukaszWojciechowski pointed out, using os.LookupEnv:

  1. func getEnv(key, fallback string) string {
  2. if value, ok := os.LookupEnv(key); ok {
  3. return value
  4. }
  5. return fallback
  6. }

答案2

得分: 54

你要找的是os.LookupEnvif语句的结合。

这是janos的答案更新后使用LookupEnv的版本:

  1. func getEnv(key, fallback string) string {
  2. value, exists := os.LookupEnv(key)
  3. if !exists {
  4. value = fallback
  5. }
  6. return value
  7. }
英文:

What you're looking for is os.LookupEnv combined with an if statement.

Here is janos's answer updated to use LookupEnv:

  1. func getEnv(key, fallback string) string {
  2. value, exists := os.LookupEnv(key)
  3. if !exists {
  4. value = fallback
  5. }
  6. return value
  7. }

答案3

得分: 24

Go在这里没有与Python完全相同的功能;我能想到的最符合惯用方式是:

  1. mongo_password := "pass"
  2. if mp := os.Getenv("MONGO_PASS"); mp != "" {
  3. mongo_password = mp
  4. }
英文:

Go doesn't have the exact same functionality as Python here; the most idiomatic way to do it though, I can think of, is:

  1. mongo_password := "pass"
  2. if mp := os.Getenv("MONGO_PASS"); mp != "" {
  3. mongo_password = mp
  4. }

答案4

得分: 19

为了保持代码的整洁,我这样做:

  1. myVar := getEnv("MONGO_PASS", "default-pass")

我定义了一个在整个应用程序中使用的函数:

  1. // getEnv 如果存在,则获取键环境变量,否则返回默认值
  2. func getEnv(key, defaultValue string) string {
  3. value := os.Getenv(key)
  4. if len(value) == 0 {
  5. return defaultValue
  6. }
  7. return value
  8. }
英文:

To have a clean code I do this:

  1. myVar := getEnv("MONGO_PASS", "default-pass")

I defined a function that is used in the whole app

  1. // getEnv get key environment variable if exist otherwise return defalutValue
  2. func getEnv(key, defaultValue string) string {
  3. value := os.Getenv(key)
  4. if len(value) == 0 {
  5. return defaultValue
  6. }
  7. return value
  8. }

答案5

得分: 3

我找到了一个人将这个帖子中的答案封装成了一个非常简单易用的库,希望这对其他人有所帮助!
https://github.com/caarlos0/env

英文:

Had the same question as the OP and found someone encapsulated the answers from this thread into a nifty library that is fairly simple to use, hope this help others!

https://github.com/caarlos0/env

答案6

得分: 2

对于更复杂的应用程序,您可以使用像viper这样的工具,它允许您设置全局自定义默认值、解析配置文件、为应用程序的环境变量键设置前缀(以确保环境变量配置的一致性和命名空间)以及许多其他很酷的功能。

示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/spf13/viper"
  5. )
  6. func main() {
  7. viper.AutomaticEnv() // 读取环境变量的值
  8. // 设置默认值
  9. viper.SetEnvPrefix("app")
  10. viper.SetDefault("linetoken", "DefaultLineTokenValue")
  11. // 声明变量
  12. linetoken := viper.GetString("linetoken")
  13. fmt.Println("---------- 示例 ----------")
  14. fmt.Println("linetoken :", linetoken)
  15. }
英文:

For more complex application you can use tooling such as viper, which allows you to set global custom default values, parse configuration files, set a prefix for your app's env var keys (to ensure consistency and name spacing of env var configurations) and many other cool features.

Sample code:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/spf13/viper"
  5. )
  6. func main() {
  7. viper.AutomaticEnv() // read value ENV variable
  8. // Set default value
  9. viper.SetEnvPrefix("app")
  10. viper.SetDefault("linetoken", "DefaultLineTokenValue")
  11. // Declare var
  12. linetoken := viper.GetString("linetoken")
  13. fmt.Println("---------- Example ----------")
  14. fmt.Println("linetoken :", linetoken)
  15. }

答案7

得分: 2

我也遇到了同样的问题,我刚刚创建了一个名为getenvs的小包,专门用来解决这个问题。

Getenvs支持stringboolintfloat类型,可以像下面这样使用:

  1. package main
  2. import (
  3. "fmt"
  4. "gitlab.com/avarf/getenvs"
  5. )
  6. func main() {
  7. value := getenvs.GetEnvString("STRING_GETENV", "default-string-value")
  8. bvalue, _ := getenvs.GetEnvBool("BOOL_GETENV", false)
  9. ivalue, _ := getenvs.GetEnvInt("INT_GETENV", 10)
  10. fmt.Println(value)
  11. fmt.Println(bvalue)
  12. fmt.Println(ivalue)
  13. }
英文:

I also had the same problem and I just created a small package called getenvs exactly to answer this problem.

Getenvs supports string, bool, int and float and it can be used like below:

  1. package main
  2. import (
  3. "fmt"
  4. "gitlab.com/avarf/getenvs"
  5. )
  6. func main() {
  7. value := getenvs.GetEnvString("STRING_GETENV", "default-string-value")
  8. bvalue, _ := getenvs.GetEnvBool("BOOL_GETENV", false)
  9. ivalue, _ := getenvs.GetEnvInt("INT_GETENV", 10)
  10. fmt.Println(value)
  11. fmt.Println(bvalue)
  12. fmt.Println(ivalue)
  13. }

答案8

得分: 1

如果你愿意增加一些依赖,你可以使用类似于https://github.com/urfave/cli的东西。

  1. package main
  2. import (
  3. "os"
  4. "github.com/urfave/cli"
  5. )
  6. func main() {
  7. app := cli.NewApp()
  8. app.Flags = []cli.Flag {
  9. cli.StringFlag{
  10. Name: "lang, l",
  11. Value: "english",
  12. Usage: "language for the greeting",
  13. EnvVar: "APP_LANG",
  14. },
  15. }
  16. app.Run(os.Args)
  17. }
英文:

In case you are OK with adding little dependency you can use something like https://github.com/urfave/cli

  1. package main
  2. import (
  3. "os"
  4. "github.com/urfave/cli"
  5. )
  6. func main() {
  7. app := cli.NewApp()
  8. app.Flags = []cli.Flag {
  9. cli.StringFlag{
  10. Name: "lang, l",
  11. Value: "english",
  12. Usage: "language for the greeting",
  13. EnvVar: "APP_LANG",
  14. },
  15. }
  16. app.Run(os.Args)
  17. }

huangapple
  • 本文由 发表于 2016年10月30日 14:21:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/40326540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定