Skip to content
/ gonfig Public
forked from tkanos/gonfig

Manage Configuration file and environment in GO

License

Notifications You must be signed in to change notification settings

g41797/gonfig

 
 

Repository files navigation

gonfig Go

Fork of github.com/tkanos/gonfig - added "using prefixes for environment variables name"

gonfig is a lightweight Golang package for integrating both JSON configs and environment variables into one config object.

Usage

First define a configuration structure:

type Configuration struct {
	Port              int
	Connection_String string
}

Then fill in our JSON file:

{
	"Port": 8080
}

We do not define Connection_String in the JSON as we would prefer to define that through an environment variable.

Best practices of configuration file

using Docker:

$ docker run [...] -e Connection_String="..." [...]

To make this simple for developers we can use gonfig to easily fill in our struct.

$ go get github.com/g41797/gonfig
import "github.com/g41797/gonfig"

configuration := Configuration{}
err := gonfig.GetConf("pathtomyjonfile.json", &configuration)
if err != nil {
	panic(err)
}

Now we can use the configuration as if it was coming from one source.

// pseudo code
if configuration.Port == 8080 {
	return true
}
if configuration.Connection_String != nil {
	return true
}

using different environment variables name

If your env variable has a different name than the json one, you can just define an env attribute

type Configuration struct {
	Port              int  `env:"MYAPP_PORT"`
	Connection_String string
}

using prefixes for environment variables name

If an env attribute was not defined , gonfig

  • looking for prefixed name
  • if this name does not exist - tries to get using former name.

Prefixed name created from the name of the configuration file.

For example for file example.json:

{
	"Port": 8080,
    "Connection_String": "connection_string"
}

prefix will be EXAMPLE_ and names of environment variables:

  • EXAMPLE_Port
  • EXAMPLE_Connection_String

This feature allows to place the same variables used in different configuration files to environment.

When should gonfig be used?

If you have a limited number of environment configuration variables, it's probably better to set the struct values yourself.

configuration.Connection_String = os.Getenv("Connection_String")

gonfig makes it easier to combine JSON and environment variables into one struct automatically.

Sample

You can find a sample of the use of Gonfig project HERE

Links

About

Manage Configuration file and environment in GO

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%