How to fix environment variables not working while running from system-d service in Go

  • A+

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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: