Go语言环境变量

151 阅读1分钟

GO里面的环境变量

go语言中对环境变量的处理采用os包里面的LookupEnv方法来获取环境变量:如果环境变量存在,那么返回变量值和true,否则返回空串和false。

下面是它的函数说明:

LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

下面是一个例子:

package main

import (
	"fmt"
	"os"
)

func main() {
	str, b := os.LookupEnv("varenv")
	if b {
		fmt.Println(str, b)
	} else {
		fmt.Println(b, "ee")
	}
}

编译:

$ go build -o env

不设环境变量先执行:

$ ./env

输出:

false ee

带上环境变量执行:

 $ varenv="this is a env var" ./env

输出:

this is a env var true

带上环境变量执行:

 $ varenv="hhhh" ./env

输出:

hhhh true

总结

引入环境变量可以让我们只需要编译一次可执行文件即可,这样我们只需要加上环境变量去运行就行。比如可以把数据库配置通过环境变量传入。