環(huán)境變量是一種用于將配置信息傳遞到Unix程序的通用機(jī)制。我們來看看如何設(shè)置,獲取和列出環(huán)境變量。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.com/go/go_environment.html
command-line-flags.go
的完整代碼如下所示 -
package main
import "os"
import "strings"
import "fmt"
func main() {
// To set a key/value pair, use `os.Setenv`. To get a
// value for a key, use `os.Getenv`. This will return
// an empty string if the key isn't present in the
// environment.
os.Setenv("FOO", "1")
fmt.Println("FOO:", os.Getenv("FOO"))
fmt.Println("BAR:", os.Getenv("BAR"))
// Use `os.Environ` to list all key/value pairs in the
// environment. This returns a slice of strings in the
// form `KEY=value`. You can `strings.Split` them to
// get the key and value. Here we print all the keys.
fmt.Println()
for _, e := range os.Environ() {
pair := strings.Split(e, "=")
fmt.Println(pair[0])
}
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run environment-variables.go
FOO: 1
BAR:
ALLUSERSPROFILE
ANDROID_HOME
APPDATA
asl.log
CommonProgramFiles
CommonProgramFiles(x86)
CommonProgramW6432
COMMPath
COMPUTERNAME
ComSpec
FOO
FPS_BROWSER_APP_PROFILE_STRING
FPS_BROWSER_USER_PROFILE_STRING
FP_NO_HOST_CHECK
GOROOT
HOMEDRIVE
HOMEPATH
JAVA_HOME
LOCALAPPDATA
LOGONSERVER
M2_HOME
MAVEN_HOME
MYSQLCONNECTOR_ASSEMBLIESPATH
NUMBER_OF_PROCESSORS
OPENSSL_CONF
OS
Path
PATHEXT
PROCESSOR_ARCHITECTURE
PROCESSOR_IDENTIFIER
PROCESSOR_LEVEL
PROCESSOR_REVISION
ProgramData
ProgramFiles
ProgramFiles(x86)
ProgramW6432
PROMPT
PSModulePath
PUBLIC
SESSIONNAME
SystemDrive
SystemRoot
TEMP
TMP
USERDOMAIN
USERDOMAIN_ROAMINGPROFILE
USERNAME
USERPROFILE
VS140COMNTOOLS
windir
windows_tracing_flags
windows_tracing_logfile