Envopts - Provides a code generator for turning env structs into functional options

envopts

Tests

Provides a code generator to turn structs annotated for the popular env library into functional options. Functional options are a common pattern in Go but a lot of boiler place is required to use them when the values come from environmnet variables. This code generator aims to solve this problem.

Furthermore it also automatically takes into account any default values specified through the "envDefault" tags. And usefull documentation is generated when a comment is specified for each struct field.

Check out the example directory with variations and options.

example:

Given the following struct for parsing env variables:

//go:generate go run github.com/fxlib/envopts -type=FooEnv

// FooEnv would describe an environment variable struct parsed using: github.com/caarlos0/env
type FooEnv struct {
	Home     string        `env:"HOME"`
	Hosts    []string      `env:"HOSTS" envSeparator:":"`
	Duration time.Duration `env:"DURATION"` // Duration of the timeout
	Foo, Dar []env.Options `env:"FOO"`
}

Running go generate will generate everything required for the functional option pattern:

// Option is a functional option to configure FooEnv
type Option func(*FooEnv)

// FromFooEnv takes fully configured FooEnv and returns it as an option. Can be used to parse environment
// variables manually and provide the result in places where an option argument is expected.
func FromFooEnv(v *FooEnv) Option {
	return func(c *FooEnv) { *c = *v }
}

// ParseEnv will parse environment variables into a slice of options. Any options for parsing the
// environment can be supplied, for example to parse under a prefix.
func ParseEnv(eo env.Options) (opts []Option, err error) {
	var o FooEnv
	opts = append(opts, FromFooEnv(&o))
	return opts, env.Parse(&o, eo)
}

// ApplyOptions will merge all options into the resulting FooEnv while also ensuring default values are
// always set.
func ApplyOptions(opts ...Option) (res FooEnv) {
	env.Parse(&res, env.Options{Environment: make(map[string]string)})
	for _, o := range opts {
		o(&res)
	}
	return
}

// WithHome configures FooEnv
func WithHome(v string) Option { return func(o *FooEnv) { o.Home = v } }

// ...

// WithDar configures FooEnv
func WithDar(v []env.Options) Option { return func(o *FooEnv) { o.Dar = v } }

This could then be used to write code that accepts functional options like this:

// FooService behaves differently based on configuration options
type FooService struct {
	cfg FooEnv
}

// NewFooService inits the FooService while taking options
func NewFooService(opts ...Option) (s *FooService) {
	s = &FooService{
		// set default values, overwritten by any explicitely configured options
		cfg: ApplyOptions(opts...),
	}
	return
}

backlog

  • We could read the 'required' tag and error when calling ApplyOptions when this is not provided. But it would required to return an extra err value and required options should be passed as separate arguments anyway.
  • Figure out if we need to take care of nested structs of env options
  • Instead of depending on goimport being present to clean up unused or used imports it would be nice if we could do everything from our own binary
  • Add comments to the generated code so developers that read it can follow what is happening. Also for godoc
  • Clean up the codebase, proper error handing in walking
  • Write proper unit tests instead of lazy smoke tests that call the Go command
  • Write some more documentation to get the point of this project across. Tell about features:
    • Comment handling
    • EnvDefautl handling
Similar Resources

๐Ÿ™ Yeoman Generator for Golang Microservices.

๐Ÿ™ Yeoman Generator for Golang Microservices.

Yeoman Generator for Golang Microservices Documentation Usage Install Yeoman $ npm install -g yo Install with NPM $ npm install generator-goapi $ yo

Jan 15, 2022

Go generator to copy values from type to type and fields from struct to struct. Copier without reflection.

Copygen is a command-line code generator that generates type-to-type and field-to-field struct code without adding any reflection or dependenc

Dec 29, 2022

Sotardok generator project

bagong Generate template add template base bagong template add --name project_name --value template_location get template bagong template get --name

Oct 20, 2021

Gofire ๐Ÿ”ฅ Command Line Interface Generator tool for Go

Gofire ๐Ÿ”ฅ Command Line Interface Generator tool for Go

Gofire ๐Ÿ”ฅ : Command Line Interface Generator tool for Go Introduction Gofire is the tool for Go that automatically generates a command line interface

Dec 6, 2022

Browser based Ascii-art generator with simple web design

Browser based Ascii-art generator with simple web design

Oct 31, 2022

An address generator for EVM, written by golang

address-generator An address generator for EVM, written by golang usage ./address-generator --help evm address generator Usage: address_generator

Dec 17, 2021

Vanity address generator for Nano

Nano Vanity Generator A basic vanity address generator for the Nano cryptocurrency. What is a vanity address? A vanity address is an address that cont

Feb 6, 2022

License-cli - simple LICENSE file generator

๐Ÿ“ license-cli simple LICENSE file generator 2022-01-04.12-28-26.mp4 Install / U

Jun 2, 2022

This project is used to get familiar with GoLang cli apps, along with cobra generator.

SecretCTL SecretCTL About the project Status Getting started Layout Notes About the project This project is used to get familiar with GoLang cli apps,

Jan 11, 2022
Related tags
AI-powered code snippet generator using ChatGPT. Generate code in various languages based on natural language descriptions!

SnipForge - AI-Powered Code Snippet Generator SnipForge is a powerful command-line interface (CLI) tool that utilizes OpenAI's GPT technology to gener

May 5, 2023
A convenience provider for reading `.env` files in Terraform.

Terraform Provider dotenv This is a convenience provider for Terraform that provides a data source for reading .env files. Using the provider Below is

Dec 23, 2022
This package to make it easy to work with env

Go Env This package to make it easy to work with env Example usage package main

Jan 30, 2022
Rinaugo - Golang library with functional capabilities

RinauGo RinauGo adds some ADT to Golang, and functional programming capabilities

Dec 13, 2022
Tag-based environment configuration for structs

env Tag-based environment configuration for structs. Installation $ go get -u github.com/codingconcepts/env Usage package main import ( "fmt" "log"

Dec 23, 2022
Integrated console application library, using Go structs as commands, with menus, completions, hints, history, Vim mode, $EDITOR usage, and more ...
Integrated console application library, using Go structs as commands, with menus, completions, hints, history, Vim mode, $EDITOR usage, and more ...

Gonsole - Integrated Console Application library This package rests on a readline console library, (giving advanced completion, hint, input and histor

Nov 20, 2022
An excellent tool for converting json files to structs or classes in any programming language.
An excellent tool for converting json files to structs or classes in any programming language.

Explore Usage ยป Report Bug ยท Request Feature Table of Contents About The Project Supported Languages Getting Started Usage Parameters Set Up Your Own

Dec 10, 2022
Code generator to produce CLI from R packages

cmd Create command line applications from R packages. How it works It's a code generator that outputs Go code which produces a Command Line Applicatio

Apr 30, 2022
Grab is a tool that downloads source code repositories into a convenient directory layout created from the repo's URL's domain and path

Grab is a tool that downloads source code repositories into a convenient directory layout created from the repo's URL's domain and path. It supports Git, Mercurial (hg), Subversion, and Bazaar repositories.

Jun 2, 2022
Sloc, Cloc and Code: scc is a very fast accurate code counter with complexity calculations and COCOMO estimates written in pure Go
Sloc, Cloc and Code: scc is a very fast accurate code counter with complexity calculations and COCOMO estimates written in pure Go

Sloc Cloc and Code (scc) A tool similar to cloc, sloccount and tokei. For counting physical the lines of code, blank lines, comment lines, and physica

Jan 8, 2023