读取.env中的环境变量
godotenv 源于一个 Ruby 的开源项目dotenv
安装方式
go get github.com/joho/godotenv
使用方式
1、手动加载
err := godotenv.Load()
if err != nil {
return
}
2、自动加载
import (
_"github.com/joho/godotenv/autoload"
)
查看 godotenv/autoload 中的源码 可见 :
package autoload
import "github.com/joho/godotenv"
func init() {
godotenv.Load()
}
其实就是在 init 函数中 调用了 Load() 方法
3、加载自定义的文件
godotenv.Load() 中 没有 传入自定义解析的 文件名 时,是默认解析 执行文件 同目录下的 .env 文件
func Load(filenames ...string) (err error) {
filenames = filenamesOrDefault(filenames)
for _, filename := range filenames {
err = loadFile(filename, false)
if err != nil {
return // return early on a spazout
}
}
return
}
支持 传入多个自定义文件,可以解析 YAML 、.env 和 同类格式的自定义文件
也支持 覆盖 原始 env 变量,使用 godotenv.Overload()
4、支持 只读取 .env 文件内容, 不写入 系统环境变量
使用 godotenv.Read() 会返回一个 envMap 集合
func Read(filenames ...string) (envMap map[string]string, err error)
5、支持 从字符串 中读取 和 支持写入 .env 文件
godotenv.Unmarshal() 从字符串读取
func Unmarshal(str string) (envMap map[string]string, err error)
将 env 变量写入 文件 godotenv.Write()
func Write(envMap map[string]string, filename string)
6、命令行模式
godotenv还提供了一个命令行的模式:
godotenv -f ./.env command args
其他具体解析代码可查看源码
源码目录
作者:joker.liu 创建时间:2022-09-14 08:40
最后编辑:joker.liu 更新时间:2022-09-14 08:40
最后编辑:joker.liu 更新时间:2022-09-14 08:40