I need to have a variable volume_path
for my project.
volume_path is set in .env file, so I have 2 definition for it:
.env
.env.testing
In my code, I will set the var to:
var Volume_path = os.Getenv("VOLUME_PATH")
I know how to do it to set this var in each file, but I would like to define it just once, and make it accesible for all the project, is it possible ?
Simply use a single variable, and refer to that single instance from everywhere you need it.
Note that you can't refer to identifiers defined in the main
package from other packages. So if you have multiple packages, this variable must be in a non-main
package. Put it in package example
, have it start with an uppercase letter (so it is exported), and import the example
package from other packages, and you can refer to it as example.Volume_path
.
Also note that the Volume_path
name is not idiomatic in Go, you should name it rather VolumePath
.
example.go
:
package example
var VolumePath = os.Getenv("VOLUME_PATH")
And in other packages:
import (
"path/to/example"
"fmt"
)
func something() {
fmt.Println(example.VolumePath)
}
The prefer way to approach this is to set instance of the variable value in a package(Other than main) and use it all around the program ,
Example:
var Volume string
var Volume = os.Getenv("VOLUME_PATH")
Please remember the following rule in go:
upper case initial letter: Name is visible to clients of package otherwise: name (or _Name) is not visible to clients of package
See Golang naming