Automatically generate Go Code from dotenv files.

goenvgen Go codecov Go Report Card

Automatically generate Go Code from dotenv files.

This cli automatically determines the type information from the dotenv information and generates a Go package that can retrieve it. os.GetEnv the code becomes complicated because of the lack of type information. This package eliminates the need to use os.GetEnv.

Usage

Installation

$ go get github.com/potproject/goenvgen

Generate Code

Add your application configuration to your .env file in the root of your project.

BASE_HOST=localhost
BASE_PORT=8080
ADMIN_IDS=123,234,345,456

USER_JSON={"Alice": {"ID": 100}, "Bob": {"ID": 200}}

The following code will be generated automatically Go Package.

$ goenvgen -p envgen .env.
Generated envgen Packages.

$ tree envgen
envgen
├── USER_JSON.go
└── envgen.go

About generated package

This package itself does not read environment variables from dotenv, so joho/godotenv is required if you want to use .env file.

This is because it may control whether the dotenv file is loaded in the production and development environments.

Example Codes:

package main

import (
	"fmt"
	"log"

	"github.com/joho/godotenv"
	"[Your package path]/envgen"
)

func main() {
	// Loading .env file
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}

	// Setup envgen package from environment variables
	err = envgen.Load()
	if err != nil {
		log.Fatal(err)
	}

	// Getting Environment Variables
	host := envgen.Get().BASE_HOST()
	port := envgen.Get().BASE_PORT()
	fmt.Printf("Running to http://%s:%d/", host, port)
  
	// Slice Type
	ids := envgen.Get().ADMIN_IDS()
	for _, id := range ids {
		fmt.Printf("ID: %d \r\n", id)
	}

	// JSON Type
	user := envgen.Get().USER_JSON()
	fmt.Printf("Bod ID: %d \r\n", user.Bob.ID)
}

Results:

$ go run main.go
Running to http://localhost:8080/
ID: 123 
ID: 234
ID: 345
ID: 456
Bob ID: 200

Enjoy Development!

Details

Usage of envgen:
  -p string
        the name of the package for the generated code (default "envgen")
  -r string
        Required Type setting (example: "-r ENV_REQ_BOOL,ENV_REQ_STRING")
  -t string
        Manually type definition setting (example: "-t ENV_BOOL=bool,ENV_S_INT=[]int")

Automatic determination of type

At the time of code generation, the type is automatically assigned from the values in the .env file.

Automatic generation is generated by the following rule.

value is Type ... Example
JSON strings Generate struct for ChimeraCoder/gojson '{"Alice": {"ID": 100}, "Bob": {"ID": 200}}'
true or false boolean 'true'
integral number int64 '123'
floating point number float64 '1.1'
true or false with comma []boolean 'true,false'
integral number with comma []int64 '100,200'
floating point number with comma []float64 '0.1,0.2'
charactor with comma []string 'string1,string2'
otherwise string 'string'

Manual determination of type

The type can be set manually by specifying the -t option when generating the code.

The types that can be set are bool, int, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, interface, and string. or their slice types.

Example:

goenvgen -p envgen -t BASE_PORT=uint16,ADMIN_IDS=[]int

Required Environment Variable

You can make the value required by specifying the -r option when generating the code.

Example:

BASE_HOST=
BASE_PORT=8080
goenvgen -p envgen -r BASE_HOST,BASE_PORT
$ go run .\main.go
BASE_HOST is required

Development & Contributing

Contributions are most welcome!

$ git clone https://https://github.com/potproject/goenvgen.git

# Code Generating Test
$ cd test
$ vi .env.test # Change .env.test File
$ go run main.go
$ go test ./envgentest/

License

MIT License

Owner
Similar Resources

Golang library for reading properties from configuration files in JSON and YAML format or from environment variables.

go-config Golang library for reading properties from configuration files in JSON and YAML format or from environment variables. Usage Create config in

Aug 22, 2022

Config files for my GitHub profile.

hcltm Threat Modeling with HCL Overview There are many different ways in which a threat model can be documented. From a simple text file, to more in-d

Dec 7, 2021

Config files for my GitHub profile.

Config files for my GitHub profile.

swag 🌍 English ∙ 简体中文 Swag converts Go annotations to Swagger Documentation 2.0. We've created a variety of plugins for popular Go web frameworks. Th

Dec 7, 2021

Quick and easy way to load config files based on a simple set of rules.

Quick and easy way to load config files based on a simple set of rules.

config Quick and easy way to load config files based on a simple set of rules. Project inspired by https://github.com/lorenwest/node-config Important

Apr 9, 2021

nflex - common interface to parsed config files

nflex - common interface to parsed config files Install: go get github.com/muir/

Dec 29, 2021

Tinyini - Bare-bones Go library for reading INI-like configuration files

tinyini tinyini is a minimalistic library for parsing INI-like configuration files. example configuration file globalkey = globalvalue [section] key

Jan 10, 2022

Config files for my GitHub profile.

Config files for my GitHub profile.

Distributed server for social and realtime games and apps. Features Users - Register/login new users via social networks, email, or device ID. Storage

Jan 13, 2022

Tmpl - A tool to apply variables from cli, env, JSON/TOML/YAML files to templates

tmpl allows to apply variables from JSON/TOML/YAML files, environment variables or CLI arguments to template files using Golang text/template and functions from the Sprig project.

Nov 14, 2022

Gonfigure - Read and write config files in go

Gonfigure Reads ini files in golang. Reading INI Files Load file File can be loa

Jan 27, 2022
🛠 A configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP
🛠 A configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP

config A small configuration library for Go that parses environment variables, JSON files, and reloads automatically on SIGHUP. Example func main() {

Dec 11, 2022
Generate initial configuration files for Go.

Generate initial configuration files for Go.

Mar 26, 2022
Library for setting values to structs' fields from env, flags, files or default tag

Configuration is a library for injecting values recursively into structs - a convenient way of setting up a configuration object. Available features:

Dec 7, 2022
Library providing routines to merge and validate JSON, YAML and/or TOML files
Library providing routines to merge and validate JSON, YAML and/or TOML files

CONFLATE Library providing routines to merge and validate JSON, YAML, TOML files and/or structs (godoc) Typical use case: Make your application config

Sep 26, 2022
A golang package for parsing ini-style configuration files

Mini Mini is a simple ini configuration file parser. The ini syntax supported includes: The standard name=value Comments on new lines starting with #

Jan 7, 2023
Manage local application configuration files using templates and data from etcd or consul

confd confd is a lightweight configuration management tool focused on: keeping local configuration files up-to-date using data stored in etcd, consul,

Dec 27, 2022
Quickly read variables from environment files

go-quick-env Quickly read variables from environment files The best way to import environment variables to your code, is by using .env files. This lib

May 11, 2021
Read files into environment variables and execute command

read-file-to-env -- Read files into environment variables and execute command Example use: read-file-to-env -one-line=HOST=/etc/hostname sh -c 'echo h

Nov 12, 2021
A simple tool that utilizes already existing libraries such as joho/godotenv to add .env-files to global path

Go dotenv A simple tool that utilizes already existing libraries such as joho/godotenv to add .env-files to global path. Created as a practical way to

Nov 15, 2021
parser for configuration files

config-loader config-loader supports to load config files and convert to map values. Supported format json Usage import ( "fmt" "github.com/tharun2

Nov 27, 2021