如何在Go中从system-d服务运行时修复环境变量不起作用

xav*_*zyl 10 go

os.Getenv("APP_PATH")用来读取系统环境变量,它正常运行应用程序的构建时工作正常.但我需要运行这个Go程序作为我使用systemd完成的服务,在这种情况下它无法读取环境变量.有什么方法可以解决这个问题吗?

Зел*_*ный 6

这取决于您运行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将加载你的变量(参见UserGroup节).


Kei*_*son 5

我们将环境变量放在 .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)

当我们以守护进程模式运行应用程序时它就可以工作


小智 5

您可以从这里开始使用环境变量。我用来在项目中实现环境变量的方法是GODOTENV go库。它很容易实现且与平台无关。

只需运行

err = godotenv.Load(filepath.Join(path_dir, ".env"))

到此为止。现在,您可以使用代码os.Getenv("APP_PATH").env文件中读取密钥,并且它与systemd服务完美配合。

  • 什么是“filePath”和“path_dir”? (2认同)