You can create the init() function and use it in main.go with a package like godotenv to set the os environment variables:
global.go file
package global import ( "log" "os" "strconv" "github.com/joho/godotenv" ) var ( SERVER_HOST string SERVER_PORT int ) func InitConfig() { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } SERVER_HOST = os.Getenv("SERVER_HOST") SERVER_PORT, _ = strconv.Atoi(os.Getenv("SERVER_PORT")) }
main.go file
package main import( G "path/to/config" ) func init() { G.InitConfig() } func main() { G.Init() }
You still have to import the βGβ package into other packages to use the variables, but I believe that the best way to solve global variables in Go (or any other languages) is to use environment variables.
source share