Godotenv - 读取.env环境变量

AI 摘要: godotenv是一个用于加载环境变量的Go语言包,可以简化服务配置过程。它将.env文件中的变量加载到环境变量中,使得在不同部署环境中存储配置变得更加便捷。

https://github.com/joho/godotenv

该包可以用在服务启动配置过程,读取.env环境变量

godotenv

在环境中存储配置是十二因素应用程序的宗旨之一。部署环境之间可能发生任何变化的任何事物,例如数据库的资源句柄或外部服务的凭据,都应从代码中提取到环境变量中。

但是,在运行多个项目的开发机器或连续集成服务器上设置环境变量并不总是可行的。

启动环境后,Dotenv将.env文件中的变量加载到ENV中。

加载本地.envFile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func TestDotEnv(t *testing.T) {
	getwd, _ := os.Getwd()
	envfile := getwd+"/../../.env"
	if err := godotenv.Load(envfile); err != nil {
		log.Fatal("Error load dot env")
	}

	s3Bucket := os.Getenv("S3_BUCKET")
	s3SecrectKey := os.Getenv("S3_SECRET_KEY")

	t.Logf("s3Bucket=>%s, s3SecerctKey=>%s\n", s3Bucket, s3SecrectKey)
}

加载yml配置文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func TestDotEnvLoad(t *testing.T) {
	// 支持YML读取
	getwd, _ := os.Getwd()
	dotfile := getwd+ "/.env.yml"
	if err := godotenv.Load(dotfile); err != nil {
		log.Fatal("Error load dot env")
	}
	foo, bar, baz := os.Getenv("FOO"), os.Getenv("BAR"), os.Getenv("BAZ")
	t.Logf("foo=>%s, bar=>%s, baz=>%s\n", foo, bar, baz)

	// 环境变量区分大小写
	t.Logf("http_proxy=>%s, https_proxy_1=>%s, https_proxy_2=>%s \n", os.Getenv("http_proxy"), os.Getenv("HTTPS_PROXY"), os.Getenv("https_proxy"))
}

加载远程配置

这个Case中,通过httptest.NewServer()创建一个测试HTTP服务,并通过ts.Client().Get(ts.URL)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func TestDotEnvLoadRemote(t *testing.T) {
	// go test http
	handler := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		jdt, _ := json.Marshal(map[string]string{
			"BUCKET_ID": "id3302",
			"BUCKET_KEY": "secret110myEnvmyEnv",
		})
		w.Write(jdt)
	}
	// new an test server
	ts := httptest.NewServer(http.HandlerFunc(handler))
	defer ts.Close()

	// request test server
	res, err := ts.Client().Get(ts.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	myEnv, err := godotenv.Parse(res.Body)
	if err != nil {
		t.Fatal(err)
	}
	t.Logf("%+v", myEnv)
}