环境变量通常被用作存储应用程序配置值的一种方式。与其将密码等敏感数据保存在代码库中,我们可以直接将它们设置为环境变量,然后程序在运行时读取。在Golang的 os包中,有一些函数可以让我们轻松地设置或取消环境变量,获取或列出环境变量,以及清除环境变量。
func Getenv(key string) string得到key环境变量的值。如果该变量未被设置,则返回空字符串。func LookupEnv(key string) (string, bool)返回key环境变量的值和一个布尔标志,如果该变量被设置,则为真。通过LookupEnv(),你可以测试环境变量是否存在。func Setenv(key, value string) error设置key环境变量的value。如果不可能,它会返回一个错误。func Unsetenv(key string) error取消设置key环境变量,如果不可能则返回错误。func Environ() []string返回所有环境变量为key=value字符串。func Clearenv()删除所有环境变量。
看一下这个例子,比较一下这些函数是如何工作的。
package main
import (
"fmt"
"log"
"os"
"strings"
)
const userKey = "GOSAMPLES_USER"
func main() {
// set environment variable
err := os.Setenv(userKey, "admin")
if err != nil {
log.Fatal(err)
}
// get environment variable
fmt.Printf("os.Getenv(): %s=%s\n", userKey, os.Getenv(userKey))
// iterate over all environment variables and check if our variable is set
for _, envStr := range os.Environ() {
if strings.HasPrefix(envStr, userKey) {
fmt.Printf("os.Environ(): %s environment variable is set: %s\n", userKey, envStr)
}
}
// lookup environment variable
val, isSet := os.LookupEnv(userKey)
fmt.Printf("os.LookupEnv(): %s variable is set: %t, value: %s\n", userKey, isSet, val)
// unset environment variable
if err := os.Unsetenv(userKey); err != nil {
log.Fatal(err)
}
// lookup environment variable again - now it should not be set
val, isSet = os.LookupEnv(userKey)
fmt.Printf("os.Unsetenv(); %s variable is set: %t, value: %s\n", userKey, isSet, val)
// clear environment variables
os.Clearenv()
fmt.Printf("os.Clearenv(): number of environment variables: %d\n", len(os.Environ()))
}
输出
os.Getenv(): GOSAMPLES_USER=admin
os.Environ(): GOSAMPLES_USER environment variable is set: GOSAMPLES_USER=admin
os.LookupEnv(): GOSAMPLES_USER variable is set: true, value: admin
os.Unsetenv(); GOSAMPLES_USER variable is set: false, value:
os.Clearenv(): number of environment variables: 0