在Go中读取和写入环境变量
环境变量是一种在运行时向程序提供动态配置信息的方法。环境变量经常被用来使同一个程序在不同的环境中工作,如本地、QA或生产环境。
在Go中获取、设置、取消设置和扩展环境变量
下面的程序演示了如何在Go中使用环境变量。它利用了os 包提供的以下函数。
-
os.Setenv(key, value)。设置一个环境变量。
-
os.Getenv(key):获取一个环境变量的值。如果环境变量不存在,它会返回空值。为了区分空值和未设置的值,使用 LookupEnv
-
os.Unsetenv(key):取消设置一个环境变量。
-
os.LookupEnv(key):获取一个环境变量的值和一个指示环境变量是否存在的布尔值。它返回一个字符串和一个布尔值 - 如果环境变量不存在,布尔值将为假。
-
os.ExpandEnv(str):通过根据当前环境变量的值替换字符串中的 var 来扩展一个字符串。
package main
import (
"fmt"
"os"
)
func main() {
// Set an Environment Variable
os.Setenv("DB_HOST", "localhost")
os.Setenv("DB_PORT", "5432")
os.Setenv("DB_USERNAME", "root")
os.Setenv("DB_PASSWORD", "admin")
os.Setenv("DB_NAME", "test")
// Get the value of an Environment Variable
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
fmt.Printf("Host: %s, Port: %s\n", host, port)
// Unset an Environment Variable
os.Unsetenv("DB_PORT")
fmt.Printf("After unset, Port: %s\n", os.Getenv("DB_PORT"))
/*
Get the value of an environment variable and a boolean indicating whether the
environment variable is present or not.
*/
driver, ok := os.LookupEnv("DB_DRIVER")
if !ok {
fmt.Println("DB_DRIVER is not present")
} else {
fmt.Printf("Driver: %s\n", driver)
}
// Expand a string containing environment variables in the form of $var or ${var}
dbURL := os.ExpandEnv("postgres://$DB_USERNAME:$DB_PASSWORD@DB_HOST:$DB_PORT/$DB_NAME")
fmt.Println("DB URL: ", dbURL)
}
# Output
Host: localhost, Port: 5432
After unset, Port:
DB_DRIVER is not present
DB URL: postgres://root:admin@DB_HOST:/test
列出并清除Go中的所有环境变量
-
os.Environ():这个函数返回一个
[]string,包含所有的环境变量,形式为key=value。 -
os.Clearenv():这个函数删除了所有的环境变量。在编写测试时,它可能会派上用场,从一个干净的环境开始。
下面的例子演示了如何使用这两个函数。
package main
import (
"fmt"
"os"
"strings"
)
func main() {
// Environ returns a copy of strings representing the environment,
// in the form "key=value".
for _, env := range os.Environ() {
// env is
envPair := strings.SplitN(env, "=", 2)
key := envPair[0]
value := envPair[1]
fmt.Printf("%s : %s\n", key, value)
}
// Delete all environment variables
os.Clearenv()
fmt.Println("Number of environment variables: ", len(os.Environ()))
}
# Output
TERM_SESSION_ID : w0t0p1:70C49068-9C87-4032-9C9B-49FB6B86687B
PATH : /Users/callicoder/.nvm/versions/node/v10.0.0/bin:/usr/local/sbin:/usr/local/sbin:/Users/callicoder/protobuf/bin:/Users/callicoder/go/bin:/Users/callicoder/vaultproject:/Users/callicoder/google-cloud-sdk/bin:/Users/callicoder/.rbenv/bin:/Users/callicoder/.rbenv/shims:/Users/callicoder/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/callicoder/Library/Android/sdk/platform-tools:/opt/flutter/bin
.... # Output truncated for brevity
Number of environment variables: 0
