env

package module
v2.0.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2025 License: MIT Imports: 17 Imported by: 1

README

env package

Designed to provide simple and useful tooling to popoulate simple structs and provide managagement and helpful services utilizing struct tags instead of package like flag or third-party solutions.

type params struct {
	Action    string `env:"A,require,order" help:"a name to use"`
	Secret    string `env:"hidden" help:"a secret"`
	Flag      bool   `default:"on"  help:"a flag setting"`
	Number    int    `default:"5" help:"a number"`
	timestamp int64  // not parsed or reported in Summary
}

func main() {
	var param params
	paths := env.NewEnv(&param)
}

Set struct params and populate by calling env.NewEnv(&param) to parse and populate the struct as shown.

  • Any default value is overloaded by system environment that is in turn overloaded by any command line values.

Supported types in env.Parser are limited to string, bool, and int.

  • Bool understands and accepts: on, yes, ok, true, and 1 and their associated negative counter parts.
  • Everything you want can be derived from these three basic types, including arrays and maps that utilize your own encoding and decoding.
    • Array can be passed or set as one,two,three and split by on comman, simarly a map can be encode as k1:v1,k1:v2 and decoded by splitting on comma and then each set split on the colon.

Struct tag element supported and descriptions.

  • env: alias,order,require,environ,hidden

    • alias support can be short form of the switch -A instead of -action
    • order makes it switchless and populated based on os.Args location index
    • require will cause hard stop when not defaulted or provided
    • environ sets all struct elements in the system envronment
    • hidden redacts the struct value in the summary report
  • default: string, bool, int values

  • help: description

Automatic -help support reports basic information, the struct field name, the alias is any, the env:tag in use, any default value and the help description.

 % go run example/main.go -help

 development
--------------------
 version 
 build   

 action         A     [or  ] default:           an action to do
 secret               [   *] default:           a secret
 flag                 [    ] default:on         a flag setting
 number               [    ] default:5          a number

A summary log reports the struct values and integrates with other env system. If more than one param is populated by env.NewENV(&param,&server), each will appear as seperate sets in the order provided in the log summary output.


% go run example/main.go run   
2024/07/10 21:19:54 |----------------------------------------|
2024/07/10 21:19:54 | MAIN ::::::::::::::::::::::: event log |
2024/07/10 21:19:54 |-----//o--------------------------------|
2024/07/10 21:19:54                                 version
2024/07/10 21:19:54                                 build
2024/07/10 21:19:54                             pid 65812
2024/07/10 21:19:54 |-----//o--------------------------------|
2024/07/10 21:19:54  action         | run
2024/07/10 21:19:54  secret         | <hidden>
2024/07/10 21:19:54  flag           | true
2024/07/10 21:19:54  number         | 5
2024/07/10 21:19:54 |----------------------------------------|
2024/07/10 21:19:54 _dev/srv
2024/07/10 21:19:54 sample: start
2024/07/10 21:19:55 main: bootstrap complete
2024/07/10 21:19:58 main: interrupt shutdown
2024/07/10 21:19:58 sample: stop
2024/07/10 21:19:58 main: shutdown initiated
2024/07/10 21:19:58 |----------------------------------------|
2024/07/10 21:19:58 main: bye
2024/07/10 21:19:58 |----------------------------------------|


  • env.NewEnv - parse and populate a param struct

  • env.Parser - parser used with NewEnv methods

  • env.Dir - ensure a directory exists

  • env.Expire - expiration file manager with graceful interface support

  • env.Graceful - graceful startup/shutdown controller

  • env.Lock - process file lock (simple in use detection)

  • env.Persist - persist and resume with data on disk

  • env.Shutdown - shutdown, not necessary with graceful controller

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Version, Build string
	Description    string
)

These var should be set externally by the build command

Functions

func Conf added in v2.0.4

func Conf(cfg interface{}, path string)

Conf populates a json object applying tag:default conf values that are overloaded by the file source when configured at the primary level; no recurrsion support

type Example struct {
	Text   string `json:"text,omitempty"`
	Number int    `json:"number,omitempty" default:"10"`
	Show bool     `json:"show,omitempty" default:"on"`
}

supports: string, int, bool

func Dir

func Dir(a ...string) string

Dir will create the directory tree when it does not exist and return a string representation of the full composite path. A file is presumed when the last element contains any of the following ._- characters and fs.FileMode is coded to 0755

func NewGraceful

func NewGraceful() *graceful

NewGraceful configurator returns *graceful and starts a shutdown controller to capture (os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) signals and waits on the <-g.context for a termination signal and waits for the g.init, g.shutdown controller shutdown to confirm all managed processes have completed tasks before the program terminates execution

func Shutdown

func Shutdown(ctx context.Context, shutdownFunc func())

Shutdown waits on control context.Context or signal.Notify; only use this when env.Graceful is not used; shutdownFunc will execute after a system or user signal is received (can be nil), however when a context.CancelFunc acutally needs to be called before exiting (or anything else for control purposes) then pass these items wrapped as the shutdownFunc; uses os.Exit(0)

ctx, cancel:= context.WithCancel(context.Backgroud())
env.Shutdown(ctx, func(){cancel()})

Types

type Expire

type Expire struct {
	Freq time.Duration // frequency of checks (default: hourly)
	// contains filtered or unexported fields
}

Expire struct

func (*Expire) Add

func (ex *Expire) Add(ttl interface{}, path ...string) *Expire

Add will register a directory/path with customized age timeframe and supports various ttl inputs

nil          default 24h
int          n * hour
string       "24h", "1h30m"

func (*Expire) Expire

func (ex *Expire) Expire() *Expire

Expire will run the registered expiration processes

func (*Expire) Silent

func (ex *Expire) Silent() *Expire

Silent flag toggle for env.Expire, writes logs on os.Stderr (default: on)

func (*Expire) Start

func (ex *Expire) Start(ctx context.Context, init *sync.WaitGroup)

Start expire service manger to check for expired files periodically based on expire.Freq setting (default: check hourly, expire after 24hr)

type Lock

type Lock struct {
	Path string        // lock directory
	TTL  time.Duration // default 1hr
}

Lock {file}.lock detection

func (*Lock) Lock

func (lk *Lock) Lock() bool

Lock tests for the presence of a current {file}.Lock and returns true when a new {file}.Lock was established; false when an existing one is present

var lock = env.Lock{Path: "/tmp", TTL: time.Hour}
if !lock.Lock() {
	return // existing lock
}
defer lk.Unlock()

func (*Lock) Unlock

func (lk *Lock) Unlock() bool

Unlock removes the current {file}.lock

type Map

type Map map[string]time.Time

Map of items with ttl

func NewMap

func NewMap() *Map

NewMap

func (*Map) Add

func (m *Map) Add(k string)

Add entry

func (*Map) Next

func (m *Map) Next(age time.Duration) func() (key string, more bool)

Next returns a function return the key; removes key when used or when older than age, when age is non-zero

type Options added in v2.0.4

type Options struct {
	Silent bool // silence log configuration output
	NoHelp bool // silence help output
	SetENV bool // set KEY=VALUE in environment
	NoExit bool // return nil instead of os.Exit(0) for version,help
}

Options for env.Configure

Silent: log configuration output
NoHelp: silences the help output
SetENV: set KEY=VALUE in environemnt

type Path added in v2.0.4

type Path struct {
	Etc, Srv, Var, Tmp string
}

Path type returned by NewENV and Configure

func Configure added in v2.0.4

func Configure(cfg ...interface{}) (path *Path)

Configure sets up the basic environment and returns environment paths; pass Options as the first item to set or specify custom configuration options to silence log and help output and env.Options.M map populates, struct initially, overloaded by environment vars, overloaded by default tag, that is then overloaded by command line swithches, in this order

func NewEnv

func NewEnv(cfg ...interface{}) (path *Path)

NewEnv that sets up the basic envrionment paths and calls the Parser to process the struct tag fields and populates any interfaces that are provided

tags
	env:"alias,order,require,environ,hidden"
	help:"description"
	default:"value" (bool, string, int)

Action string `env:"A,require" default:"server" help:"action [server|client]"`

type Persist

type Persist string

Persist type

func (Persist) Load

func (p Persist) Load(persist interface{}, ttl *time.Duration) bool

Load persist object from disk or remove when older than stated ttl; ignores auto expiration when ttl is nil or 0

func (Persist) Save

func (p Persist) Save(persist interface{}) bool

Save persist object to disk; accepts anything

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL