Skip to content

An very lightweight library for dotenv files or for formatting already imported variables.

License

Notifications You must be signed in to change notification settings

gowizzard/dotenv

Repository files navigation

dotenv

.ENV

GitHub go.mod Go version of a Go module Go CodeQL CompVer Go Reference Go Report Card GitHub issues GitHub forks GitHub stars GitHub license

With this lightweight library you can read a local file with environment variables into your project. Additionally, you can use functions to read the data and the variable will be returned directly in the desired type.

Installation

First you have to install the package. You can do this as follows:

go get github.com/gowizzard/dotenv/v2

How to use

Import variables

If you want to read your local .env file, so you can use these variables in your project, you can use this function for that.

With this function the data will be loaded from the file and set as local variables. After that you can read them with standard functions, or you can use the following functions.

Here you can find the regex expression which is used to read the environment variables.

err := dotenv.Import(".env")
if err != nil {
    panic(err)
}

Read variables

If you don't want to work with the standard golang function func Getenv(key string) string from the package os or func Getenv(key string) (value string, found bool) from package syscall, because you want to output the variables directly in a certain type, then you can use the following different functions.

The functions check directly if the desired variable is available and returns the value. If the value is not available, then the default value of the type is returned.

You can also use these functions without the import function if the variables are already available locally.

Boolean

With this function you can read an environment variable and return it directly as type bool.

result := dotenv.Boolean("KEY")
println(result)

Float

With this function you can read an environment variable and return it directly as type float64. In this function you must not only specify the desired key, but also the bit size of the float type. The bit size can be between 0 to 64.

result := dotenv.Float("KEY", 64)
println(result)

Integer

With this function you can read an environment variable and return it directly as type int64. In this function, the base and the bit size must be specified in addition to the key. The base must contain one of the following values 0, 2 to 36 and the bit size can be between 0 to 64.

result := dotenv.Integer("KEY", 10, 64)
println(result)

String

With this function you can read an environment variable and return it directly as type string.

result := dotenv.String("KEY")
println(result)

Special thanks

Thanks to JetBrains for supporting me with this and other open source projects.