在文件之间使用环境变量-GOPATH [英] Using Environment Variables across files - GOPATH
问题描述
这是我第一次在Go中进行编码,而没有使用GOPATH.
我有一个go.mod
文件.
我正在尝试通过Sendgrid发送电子邮件;我有一个包含我的SENDGRID_API_KEY的文件,名为sendgrid.env
.
当尝试使用我的main.go
文件中的密钥时,该值未通过.
This is my first time coding in Go without using GOPATH.
I have a go.mod
file.
I'm attempting to send an email through Sendgrid; I have a file which contains my SENDGRID_API_KEY called sendgrid.env
.
When trying to use the key within my main.go
file, the value isn't being pulled through.
fmt.Println(os.LookupEnv("SENDGRID_API_KEY")) // empty string
fmt.Println(os.Getenv("SENDGRID_API_KEY")) // empty string
我还使用了'LookupEnv',它返回false.
任何帮助,将不胜感激.
I've also used 'LookupEnv' which returns false.
Any help would be appreciated.
推荐答案
os.Getenv()
和 os.LookupEnv()
不会检查文件.如果您的环境变量在文件中,则必须自己加载它们.或者使用为您执行此操作的第三方库,例如 github.com/joho/godotenv
,如下所示:
os.Getenv()
and os.LookupEnv()
do not check files. If your env vars are in files, you have to load them yourself. Or use a 3rd party lib that does that for you, e.g. github.com/joho/godotenv
, which would look like this:
if err := godotenv.Load("sendgrid.env"); err != nil {
log.Fatal("Error loading sendgrid.env file")
}
另一种选择是在启动您的应用程序之前导出环境变量,例如:
Another option is to export the env vars before launching your app, e.g.:
export SENDGRID_API_KEY=mykey
./mygoapp
或一行:
SENDGRID_API_KEY=mykey ./mygoapp
或者,如果文件中包含环境变量,则可以使用source
命令:
Or if you have the env vars in a file, you may use the source
command:
source sendgrid.env
./mygoapp
这篇关于在文件之间使用环境变量-GOPATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!