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?
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.
Systemd Files and Paths Unit files are stored in the /usr/lib/systemd directory and its subdirectories, while the /etc/systemd/ directory and its subdirectories contain symbolic links to the unit files necessary to the local configuration of the host. We recommend putting your scripts in /etc/systemd/system .
Go default Environment variables Module source code outside the cache may be stored in any directory. If GOPATH is not set, it defaults to the go subdirectory of the user's home directory.
Working With Environment Variables in Go 1 Handling Credentials. If you are writing distributed systems in Go, the best practice when it comes to configuration is to store it in the environment. 2 Reading Environment Variables. ... 3 Setting Environment Variables. ... 4 Feature Flags. ... 5 Setup Of Environment Variables. ... 6 Conclusion. ...
Head past the break to fix it by properly setting the buried System Environment Variables. Open the start menu and type “system environment variables” and hit enter or open the start menu and navigate to Control Panel>System and Security>System>Advanced system settings(up and on the left). Click on Environment Variables to open this window.
If that's why you want to pass an environment variable to your service, do notuse Environment=in the unit configuration file. Use EnvironmentFile=and point it to another configuration file that is only readable by the service account (and users with root access).
The path environment variables aren’t all populated by users. There are a few default paths that are part of it. Users can always add or remove them. If you’ve accidentally deleted a single path environment variable, or all of them, you can add them back.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With