英文:
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 来处理。
但是你可以创建一个辅助函数来简化操作:
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
需要注意的是,正如 @michael-hausenblas 在评论中指出的那样,如果环境变量的值真的为空,你将得到回退值。
正如 @ŁukaszWojciechowski 指出的,更好的方法是使用 os.LookupEnv
:
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
英文:
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:
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
return fallback
}
return value
}
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
:
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
答案2
得分: 54
你要找的是os.LookupEnv
与if
语句的结合。
这是janos的答案更新后使用LookupEnv的版本:
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
英文:
What you're looking for is os.LookupEnv
combined with an if
statement.
Here is janos's answer updated to use LookupEnv:
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
答案3
得分: 24
Go在这里没有与Python完全相同的功能;我能想到的最符合惯用方式是:
mongo_password := "pass"
if mp := os.Getenv("MONGO_PASS"); mp != "" {
mongo_password = mp
}
英文:
Go doesn't have the exact same functionality as Python here; the most idiomatic way to do it though, I can think of, is:
mongo_password := "pass"
if mp := os.Getenv("MONGO_PASS"); mp != "" {
mongo_password = mp
}
答案4
得分: 19
为了保持代码的整洁,我这样做:
myVar := getEnv("MONGO_PASS", "default-pass")
我定义了一个在整个应用程序中使用的函数:
// getEnv 如果存在,则获取键环境变量,否则返回默认值
func getEnv(key, defaultValue string) string {
value := os.Getenv(key)
if len(value) == 0 {
return defaultValue
}
return value
}
英文:
To have a clean code I do this:
myVar := getEnv("MONGO_PASS", "default-pass")
I defined a function that is used in the whole app
// getEnv get key environment variable if exist otherwise return defalutValue
func getEnv(key, defaultValue string) string {
value := os.Getenv(key)
if len(value) == 0 {
return defaultValue
}
return value
}
答案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!
答案6
得分: 2
对于更复杂的应用程序,您可以使用像viper
这样的工具,它允许您设置全局自定义默认值、解析配置文件、为应用程序的环境变量键设置前缀(以确保环境变量配置的一致性和命名空间)以及许多其他很酷的功能。
示例代码:
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main() {
viper.AutomaticEnv() // 读取环境变量的值
// 设置默认值
viper.SetEnvPrefix("app")
viper.SetDefault("linetoken", "DefaultLineTokenValue")
// 声明变量
linetoken := viper.GetString("linetoken")
fmt.Println("---------- 示例 ----------")
fmt.Println("linetoken :", linetoken)
}
英文:
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:
package main
import (
"fmt"
"github.com/spf13/viper"
)
func main() {
viper.AutomaticEnv() // read value ENV variable
// Set default value
viper.SetEnvPrefix("app")
viper.SetDefault("linetoken", "DefaultLineTokenValue")
// Declare var
linetoken := viper.GetString("linetoken")
fmt.Println("---------- Example ----------")
fmt.Println("linetoken :", linetoken)
}
答案7
得分: 2
我也遇到了同样的问题,我刚刚创建了一个名为getenvs的小包,专门用来解决这个问题。
Getenvs支持string
、bool
、int
和float
类型,可以像下面这样使用:
package main
import (
"fmt"
"gitlab.com/avarf/getenvs"
)
func main() {
value := getenvs.GetEnvString("STRING_GETENV", "default-string-value")
bvalue, _ := getenvs.GetEnvBool("BOOL_GETENV", false)
ivalue, _ := getenvs.GetEnvInt("INT_GETENV", 10)
fmt.Println(value)
fmt.Println(bvalue)
fmt.Println(ivalue)
}
英文:
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:
package main
import (
"fmt"
"gitlab.com/avarf/getenvs"
)
func main() {
value := getenvs.GetEnvString("STRING_GETENV", "default-string-value")
bvalue, _ := getenvs.GetEnvBool("BOOL_GETENV", false)
ivalue, _ := getenvs.GetEnvInt("INT_GETENV", 10)
fmt.Println(value)
fmt.Println(bvalue)
fmt.Println(ivalue)
}
答案8
得分: 1
如果你愿意增加一些依赖,你可以使用类似于https://github.com/urfave/cli的东西。
package main
import (
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "lang, l",
Value: "english",
Usage: "language for the greeting",
EnvVar: "APP_LANG",
},
}
app.Run(os.Args)
}
英文:
In case you are OK with adding little dependency you can use something like https://github.com/urfave/cli
package main
import (
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "lang, l",
Value: "english",
Usage: "language for the greeting",
EnvVar: "APP_LANG",
},
}
app.Run(os.Args)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论