How to create global variables once when app is launched in Go?

Issue

Good day for all readers!

I have api service which needs key for some decrypt issues. Key calculates all time when I make request. That is wrong from an architectural point of view.

The option with environments (.env, viper…) drops because, in the future, I want to bring out this module to a separate library.

Hint me, how it is possible without using environments to calculate the key when starting the application and use it until stopping the application?

Solution

A global var starts with a capital, so it is reachable from within other packages.

But… it’s actually bad behaviour, because those other packages can change it.

Having a non capital one, still means that functions in the same package can change it.

Perhaps you can use a constant?
or make a singleton variable, see :

https://goplay.tools/snippet/9k7FLYbbvoo

Answered By – Marcelloh

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.