Golang中对环境变量的获取、设置、列表和其他操作

1,180 阅读1分钟

环境变量通常被用作存储应用程序配置值的一种方式。与其将密码等敏感数据保存在代码库中,我们可以直接将它们设置为环境变量,然后程序在运行时读取。在Golang的 os包中,有一些函数可以让我们轻松地设置或取消环境变量,获取或列出环境变量,以及清除环境变量。

看一下这个例子,比较一下这些函数是如何工作的。

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