我os.Getenv("APP_PATH")
用来读取系统环境变量,它正常运行应用程序的构建时工作正常.但我需要运行这个Go程序作为我使用systemd完成的服务,在这种情况下它无法读取环境变量.有什么方法可以解决这个问题吗?
这取决于您运行systemd服务的方式.Systemd提供了一堆你应该使用的derictive:
[Unit]
Description=My service
After=network.target
[Service]
Type=simple
User=user
Group=user
EnvironmentFile=/home/user/env_file
ExecStart=/bin/bash -c -l '/home/user/go_program'
# ... other directive goes here
[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)
EnvironmentFile
- 带有ENV变量的文件,systemd将为您加载该文件.
User
,Group
- 应该运行程序的用户和组.
ExecStart=/bin/bash -c -l '/home/user/go_program'
- -l
选项使bash的行为好像它已作为登录shell调用,因此.bash_profile
将加载你的变量(参见User
和Group
节).我们将环境变量放在 .env 文件中并使用godotenv
import {
"github.com/joho/godotenv"
}
func main() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
environmentPath := filepath.Join(dir, ".env")
err = godotenv.Load(environmentPath)
fatal(err)
}
Run Code Online (Sandbox Code Playgroud)
当我们以守护进程模式运行应用程序时它就可以工作
归档时间: |
|
查看次数: |
1083 次 |
最近记录: |