如何修复从Go中的system-d服务运行时无法运行的环境变量

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?

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.

We have our environment variables in a .env file and use 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)
    }

and it works when we run our apps in daemon mode

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

[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
  • 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).