Go环境变量实例

Go环境变量实例

环境变量是一种用于将配置信息传递到Unix程序的通用机制。我们来看看如何设置,获取和列出环境变量。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.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])
    }
}

执行上面代码,将得到以下输出结果 -

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

目录