Skip to content

Environment variables #29

@Valery-Lapurin

Description

@Valery-Lapurin

A developer can create local .env file and add it in git ignore.
He can then store environment variables for his local development there (such as secrets).
Docker out of the box supports .env file, so running in a container those are accessible via os.Getenv(). But in order for those to be accessible also in local Go set up, you can do godotenv.Load(".env") first.

If you want to avoid manual call of os.Getenv() for each environment variable + get use of default values + have some support of data types, you can create struct that would contain fields named the same way as your environment variables are named - then you pass the struct to envconfig.Process("", &environmentVariables) which enriches the instance with values via reflection.

package variables

import (
	"github.com/joho/godotenv"
	"github.com/kelseyhightower/envconfig"
)

type Specification struct {
	RABBITMQ_CF_SERVICE_NAME    string `default:"rabbitmqent"`
	RABBITMQ_USERNAME          string `default:"User_01"`
	RABBITMQ_PASSWORD           string `required:"true"`
	RABBITMQ_PORT               int    `default:"5672"`
}

var environmentVariables Specification

func InitInstance() {
	godotenv.Load(".env")
	err := envconfig.Process("", &environmentVariables)
	if err != nil {
		panic(err)
	}
}

func GetInstance() Specification {
	return environmentVariables
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions