golang从文件或字符串加载环境变量插件库gotenv的使用

golang从文件或字符串加载环境变量插件库gotenv的使用

gotenv是一个Go语言库,用于从.env文件或io.Reader加载环境变量。

基本用法

首先在import语句中添加gotenv包:

import "github.com/subosito/gotenv"

gotenv提供了2个主要函数来修改应用环境变量:

  • gotenv.Load
  • gotenv.Apply

从.env文件加载

默认情况下,gotenv.Load会在当前工作目录中查找名为.env的文件。

package main

import (
	"github.com/subosito/gotenv"
	"log"
	"os"
)

func init() {
	gotenv.Load() // 加载.env文件
}

func main() {
	log.Println(os.Getenv("APP_ID"))     // "1234567"
	log.Println(os.Getenv("APP_SECRET")) // "abcdef"
}

假设你的.env文件内容如下:

APP_ID=1234567
APP_SECRET=abcdef

加载多个文件

你可以加载多个文件,按顺序加载,第一个设置的变量值会生效:

gotenv.Load(".env.production", "credentials")

从字符串加载

gotenv.Apply允许你使用任何io.Reader来加载环境变量:

gotenv.Apply(strings.NewReader("APP_ID=1234567"))

log.Println(os.Getenv("APP_ID"))
// 输出: "1234567"

覆盖现有环境变量

默认情况下,gotenv.Loadgotenv.Apply不会覆盖已存在的环境变量。如果需要覆盖,可以使用:

  • gotenv.OverLoad
  • gotenv.OverApply

示例:

os.Setenv("HELLO", "world")

// 使用Apply会保留现有值
gotenv.Apply(strings.NewReader("HELLO=universe"))
fmt.Println(os.Getenv("HELLO"))
// 输出: "world"

// 使用OverApply会覆盖现有值
gotenv.OverApply(strings.NewReader("HELLO=universe"))
fmt.Println(os.Getenv("HELLO"))
// 输出: "universe"

错误处理

gotenv.Loadgotenv.OverLoad在出错时会返回错误。gotenv还提供了gotenv.Must辅助函数,可以在出错时触发panic:

err := gotenv.Load(".env-is-not-exist")
fmt.Println("error", err)
// 错误: open .env-is-not-exist: no such file or directory

gotenv.Must(gotenv.Load, ".env-is-not-exist")
// 会触发panic
// panic: open .env-is-not-exist: no such file or directory

解析环境变量

gotenv还提供了ParseStrictParse函数作为公共API,可以从任何io.Reader解析环境变量:

// import "strings"

pairs := gotenv.Parse(strings.NewReader("FOO=test\nBAR=$FOO"))
// gotenv.Env{"FOO": "test", "BAR": "test"}

pairs, err := gotenv.StrictParse(strings.NewReader(`FOO="bar"`))
// gotenv.Env{"FOO": "bar"}

Parse会忽略无效行并返回有效环境变量的Env,而StrictParse会对无效行返回错误。


更多关于golang从文件或字符串加载环境变量插件库gotenv的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang从文件或字符串加载环境变量插件库gotenv的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用gotenv加载环境变量

gotenv是一个Go语言库,用于从文件或字符串加载环境变量。它类似于Ruby的dotenv库,可以方便地从.env文件加载配置到环境变量中。

安装gotenv

首先需要安装gotenv库:

go get github.com/subosito/gotenv

基本用法

1. 从文件加载环境变量

package main

import (
	"fmt"
	"log"
	"github.com/subosito/gotenv"
)

func main() {
	// 从.env文件加载环境变量
	err := gotenv.Load(".env")
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	// 现在可以通过os.Getenv访问这些变量
	fmt.Println("DB_HOST:", os.Getenv("DB_HOST"))
	fmt.Println("DB_PORT:", os.Getenv("DB_PORT"))
}

2. 从字符串加载环境变量

package main

import (
	"fmt"
	"log"
	"github.com/subosito/gotenv"
	"strings"
)

func main() {
	envString := `
		APP_NAME=MyApp
		APP_ENV=production
		APP_DEBUG=false
	`

	// 从字符串加载环境变量
	err := gotenv.Load(strings.NewReader(envString))
	if err != nil {
		log.Fatal("Error loading environment from string")
	}

	fmt.Println("APP_NAME:", os.Getenv("APP_NAME"))
	fmt.Println("APP_ENV:", os.Getenv("APP_ENV"))
	fmt.Println("APP_DEBUG:", os.Getenv("APP_DEBUG"))
}

高级用法

1. 覆盖现有环境变量

默认情况下,gotenv不会覆盖已存在的环境变量。如果需要覆盖,可以使用gotenv.OverLoad:

err := gotenv.OverLoad(".env")
if err != nil {
	log.Fatal("Error loading .env file")
}

2. 从多个文件加载

// 先加载.env文件,然后加载.env.local文件
// .env.local中的值会覆盖.env中的值
err := gotenv.Load(".env", ".env.local")
if err != nil {
	log.Fatal("Error loading .env files")
}

3. 解析但不直接设置环境变量

如果你只想解析环境变量而不直接设置它们:

envMap, err := gotenv.Parse(".env")
if err != nil {
	log.Fatal("Error parsing .env file")
}

// envMap是一个map[string]string
fmt.Println("DB_HOST:", envMap["DB_HOST"])

.env文件格式

.env文件支持以下格式:

# 这是注释
DB_HOST=localhost
DB_PORT=5432
DB_USER=admin
DB_PASS="password with spaces"

注意事项

  1. gotenv不会修改已存在的环境变量(除非使用OverLoad)
  2. 变量值可以用双引号括起来,包含空格时需要这样做
  3. #开头的行被视为注释
  4. 每行应该是一个键值对,格式为KEY=VALUE

完整示例

package main

import (
	"fmt"
	"log"
	"os"
	"github.com/subosito/gotenv"
)

func main() {
	// 加载.env文件
	err := gotenv.Load()
	if err != nil {
		log.Println("No .env file found or error loading it")
	}

	// 设置默认值
	if os.Getenv("APP_PORT") == "" {
		os.Setenv("APP_PORT", "8080")
	}

	// 使用环境变量
	fmt.Printf("Starting %s on port %s\n", 
		os.Getenv("APP_NAME"), 
		os.Getenv("APP_PORT"))
}

gotenv是一个简单但强大的工具,特别适合在开发环境中管理配置,可以避免将敏感信息硬编码在代码中。

回到顶部