Read .env file and load environment variables. This libaray allows to list required env variables and validate from all loaded environment variables.
Example for valid .env file names:
.env
local.env
.env.local
Library:
go get github.com/soumayg9673/dotenvAdd configuration file .env file in the root of your project or know the relative path for the file:
SERVER_ADDR=8080
SERVER_ENV=developmentIn your Go application, load the .env file
package main
import(
"log"
"github.com/soumayg9673/soumayg9673"
)
func main() {
dotenv.AddRqdKey("SERVER_ADD", true)
dotenv.AddRqdKey("SERVER_ENV", true)
if err := dotenv.LoadEnvFile(".env"); err != nil {
log.Println(err)
return
}
fmt.Println(dotenv.GetInt("SERVER_ADD", ":8000"))
fmt.Println(dotenv.GetString("SERVER_ENV", "local"))
if err := dotenv.ValidateRqdEnv(); err != nil {
log.Println(err)
return
}
}We have exposed API to customize the error messages for each scenarios:
func main() {
// Usage of constant dotenv.ERR_NO_KEY
dotenv.SetErrorMsg("%s key not found", dotenv.ERR_NO_KEY)
}func main() {
// Usage of constant dotenv.ERR_NO_KEY_VALUE
dotenv.SetErrorMsg("%s key-value pair not found", dotenv.ERR_NO_KEY_VALUE)
}func main() {
// Usage of constant dotenv.ERR_NO_VALUE
dotenv.SetErrorMsg("value for key %s not found", dotenv.ERR_NO_VALUE)
}There are multiple ways to use .env files for secrets and following are the best practices being followed by developers.
In .env file:
SERVER_ADDR=8080
SERVER_ENV=prod
PSQL_DB_NAME=postgres
PSQL_DB_HOST=localhost
PSQL_DB_PORT=5432
PSQL_DB_USER=postgres
PSQL_DB_PWD=adminIn .env file:
SERVER_ADDR=8080
SERVER_ENV=prod
In .env.prod file:
PSQL_DB_NAME=postgres
PSQL_DB_HOST=localhost
PSQL_DB_PORT=5432
PSQL_DB_USER=postgres
PSQL_DB_PWD=adminContributions are highly recommended.
Raise an issue for the following:
- Queries
- Contributing to library