Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go环境变量实例
Go环境变量实例
作者:--    发布时间:2019-11-20

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

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

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

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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册