2019-01-31 08:24
浏览 149


I am using os.Getenv("APP_PATH") to read from the system environment variables and it works fine when running the build of the application normally. But I need to run this Go program as a service which I have done using systemd in which case it cannot read the environment variables. Is there any way of resolving this?

图片转代码服务由CSDN问答提供 功能建议

我正在使用 os.Getenv(“ APP_PATH”)从系统环境中读取 变量,并且在正常运行应用程序版本时可以正常工作。 但是我需要将此Go程序作为服务运行,这是使用systemd完成的,在这种情况下,它无法读取环境变量。 有什么办法解决这个问题?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douqie1816
    douqie1816 2019-01-31 08:38

    You can follow along from here to make the use of the environment variables. The way I am using to implement environment variables in my project is GODOTENV go library. It is very easy to implement and platform independent.

    Simply run

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

    and you are done. Now you can use you code os.Getenv("APP_PATH") to read the keys from your .env file and it works perfectly fine with systemd service.

    点赞 评论
  • douhang8991
    douhang8991 2019-01-31 08:31

    We have our environment variables in a .env file and use godotenv

        import {
        func main() {
            dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
            if err != nil {
            environmentPath := filepath.Join(dir, ".env")
            err = godotenv.Load(environmentPath)

    and it works when we run our apps in daemon mode

    点赞 评论
  • dongzhan7253
    dongzhan7253 2019-01-31 08:48

    It depends on how you're running your systemd service. Systemd provide a bunch of derictive you should use:

    Description=My service
    ExecStart=/bin/bash -c -l '/home/user/go_program'
    # ... other directive goes here
    • EnvironmentFile - the file with ENV variables, that file will be loaded for you by systemd.

    • User, Group - under which user and group the program should run.

    • ExecStart=/bin/bash -c -l '/home/user/go_program' - the -l options makes bash act as if it had been invoked as a login shell, so the variable in your .bash_profile will be loaded(see User and Group section).
    点赞 评论