Skip to content

morkid/goenvi

Repository files navigation

goenvi - Simple golang environment initializer

Go Reference Github Actions Go Report Card GitHub release (latest SemVer)

Initialize your environment variables in one shot. goenvi is built on top of Viper.

Install dependency:

go get github.com/morkid/goenvi

Supported config file:

How to use goenvi

cat .env

MESSAGE="hello world"

cat main.go

package main

import (
    "os"
    "fmt",
    "github.com/morkid/goenvi"
    "github.com/spf13/viper"
)

func main() {
    goenvi.Initialize()

    fmt.Println(os.Getenv("MESSAGE"))
    fmt.Println(viper.GetString("MESSAGE"))
}

go run main.go

hello world
hello world

By default goenvi autoload .env file in current working directory.

Load custom config file

cat config.json

{
    "version": {
        "number": 1,
        "name": "v1.0.0"
    }
}

cat main.go

package main

import (
    "os"
    "fmt"
    "github.com/morkid/goenvi"
    "github.com/spf13/viper"
)

func main() {
    goenvi.Add("json", "config.json")
    goenvi.Initialize()

    fmt.Println(os.Getenv("VERSION_NUMBER"))
    fmt.Println(os.Getenv("VERSION_NAME"))
    fmt.Println(viper.GetInt("version.number"))
    fmt.Println(viper.GetInt("version.name"))
}

Multiple variations in one shot

cat main.go

package main

import (
    "os"
    "fmt"
    "github.com/morkid/goenvi"
    ...
)

func main() {
    goenvi.Add("properties", "config.properties")
    goenvi.Add("json", "config.json") // override properties if variable or file does not exists
    goenvi.Add("toml", "config.toml") // override json if variable or file does not exists
    goenvi.Add("yaml", "config.yaml") // override toml if variable or file does not exists
    goenvi.Add("dotenv", ".env") // override yaml if variable or file does not exists
    goenvi.Initialize()

    fmt.Println(os.Getenv("VERSION_NUMBER"))
    fmt.Println(os.Getenv("VERSION_NAME"))
    fmt.Println(viper.GetInt("version.number"))
    fmt.Println(viper.GetInt("version.name"))
}

Register custom viper instance

func main() {
    myEnv := viper.New()
    goenvi.Register(myEnv, true) // false if you want to load after .env loaded
    goenvi.Initialize()
}

Register command-line parameters as environment

by implementing goenvi.FlagSetProvider interface, you can register command-line parameters as environment variables.

import (
    "github.com/morkid/goenvi"
    "github.com/spf13/pflag"
    "github.com/spf13/viper"
)

type myFlagSet struct {}
func (myFlagSet) VisitAll(fn func(*pflag.FlagSet)) {
    defaultValue := viper.GetString("message")
    pflag.String("message", defaultValue, "message to show")
    pflag.Parse()

    fn(pflag.CommandLine)
}

func main() {
    goenvi.AddFlagSetProvider(myFlagSet{})
    goenvi.Initialize()
}

Note:
pflag will override some environment variables if command-line parameters specified

License

Published under the MIT License.