1
0
Fork 0
mirror of https://github.com/documize/community.git synced 2025-07-24 07:39:43 +02:00

refactored flag/env loading

This commit is contained in:
Harvey Kandola 2017-07-19 18:47:01 +01:00
parent dc49dbbeff
commit 68130122e7
23 changed files with 1128 additions and 909 deletions

126
core/env/flags.go vendored
View file

@ -9,8 +9,7 @@
//
// https://documize.com
// Package env allow environment variables to be obtained from either the environment or the command line.
// Environment variables are always uppercase, with the Prefix; flags are always lowercase without.
// Package env provides runtime, server level setup and configuration
package env
import (
@ -22,102 +21,125 @@ import (
"sync"
)
// CallbackT is the type signature of the callback function of GetString().
type CallbackT func(*string, string) bool
// Flags provides access to environment and command line switches for this program.
type Flags struct {
DBConn string // database connection string
Salt string // the salt string used to encode JWT tokens
SSLCertFile string // (optional) name of SSL certificate PEM file
SSLKeyFile string // (optional) name of SSL key PEM file
HTTPPort string // (optional) HTTP or HTTPS port
ForceHTTPPort2SSL string // (optional) HTTP that should be redirected to HTTPS
SiteMode string // (optional) if 1 then serve offline web page
}
type varT struct {
// SSLEnabled returns true if both cert and key were provided at runtime.
func (f *Flags) SSLEnabled() bool {
return f.SSLCertFile != "" && f.SSLKeyFile != ""
}
type flagItem struct {
target *string
name, setter, value string
required bool
callback CallbackT
}
type varsT struct {
vv []varT
type progFlags struct {
items []flagItem
}
var vars varsT
var varsMutex sync.Mutex
// Len is part of sort.Interface.
func (v *varsT) Len() int {
return len(v.vv)
func (v *progFlags) Len() int {
return len(v.items)
}
// Swap is part of sort.Interface.
func (v *varsT) Swap(i, j int) {
v.vv[i], v.vv[j] = v.vv[j], v.vv[i]
func (v *progFlags) Swap(i, j int) {
v.items[i], v.items[j] = v.items[j], v.items[i]
}
// Less is part of sort.Interface.
func (v *varsT) Less(i, j int) bool {
return v.vv[i].name < v.vv[j].name
func (v *progFlags) Less(i, j int) bool {
return v.items[i].name < v.items[j].name
}
// Prefix provides the prefix for all Environment variables
const Prefix = "DOCUMIZE"
// prefix provides the prefix for all environment variables
const prefix = "DOCUMIZE"
const goInit = "(default)"
// GetString sets-up the flag for later use, it must be called before ParseOK(), usually in an init().
func GetString(target *string, name string, required bool, usage string, callback CallbackT) {
varsMutex.Lock()
defer varsMutex.Unlock()
var flagList progFlags
var loadMutex sync.Mutex
// ParseFlags loads command line and OS environment variables required by the program to function.
func ParseFlags() (f Flags) {
var dbConn, jwtKey, siteMode, port, certFile, keyFile, forcePort2SSL string
register(&jwtKey, "salt", false, "the salt string used to encode JWT tokens, if not set a random value will be generated")
register(&certFile, "cert", false, "the cert.pem file used for https")
register(&keyFile, "key", false, "the key.pem file used for https")
register(&port, "port", false, "http/https port number")
register(&forcePort2SSL, "forcesslport", false, "redirect given http port number to TLS")
register(&siteMode, "offline", false, "set to '1' for OFFLINE mode")
register(&dbConn, "db", true, `'username:password@protocol(hostname:port)/databasename" for example "fred:bloggs@tcp(localhost:3306)/documize"`)
parse("db")
f.DBConn = dbConn
f.ForceHTTPPort2SSL = forcePort2SSL
f.HTTPPort = port
f.Salt = jwtKey
f.SiteMode = siteMode
f.SSLCertFile = certFile
f.SSLKeyFile = keyFile
return f
}
// register prepares flag for subsequent parsing
func register(target *string, name string, required bool, usage string) {
loadMutex.Lock()
defer loadMutex.Unlock()
name = strings.ToLower(strings.TrimSpace(name))
setter := Prefix + strings.ToUpper(name)
setter := prefix + strings.ToUpper(name)
value := os.Getenv(setter)
if value == "" {
value = *target // use the Go initialized value
setter = goInit
}
flag.StringVar(target, name, value, usage)
vars.vv = append(vars.vv, varT{target: target, name: name, required: required, callback: callback, value: value, setter: setter})
flagList.items = append(flagList.items, flagItem{target: target, name: name, required: required, value: value, setter: setter})
}
var showSettings = flag.Bool("showsettings", false, "if true, show settings in the log (WARNING: these settings may include passwords)")
// parse loads flags from OS environment and command line switches
func parse(doFirst string) {
loadMutex.Lock()
defer loadMutex.Unlock()
// Parse calls flag.Parse() then checks that the required environment variables are all set.
// It should be the first thing called by any main() that uses this library.
// If all the required variables are not present, it prints an error and calls os.Exit(2) like flag.Parse().
func Parse(doFirst string) {
varsMutex.Lock()
defer varsMutex.Unlock()
flag.Parse()
sort.Sort(&vars)
sort.Sort(&flagList)
for pass := 1; pass <= 2; pass++ {
for vi, v := range vars.vv {
for vi, v := range flagList.items {
if (pass == 1 && v.name == doFirst) || (pass == 2 && v.name != doFirst) {
typ := "Optional"
if v.value != *(v.target) || (v.value != "" && *(v.target) == "") {
vars.vv[vi].setter = "-" + v.name // v is a local copy, not the underlying data
}
if v.callback != nil {
if v.callback(v.target, v.name) {
vars.vv[vi].setter = "setting:" + v.name // v is a local copy, not the underlying data
}
flagList.items[vi].setter = "-" + v.name // v is a local copy, not the underlying data
}
if v.required {
if *(v.target) == "" {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, "In order to run", os.Args[0], "the following must be provided:")
for _, vv := range vars.vv {
for _, vv := range flagList.items {
if vv.required {
fmt.Fprintf(os.Stderr, "* setting from environment variable '%s' or flag '-%s' or an application setting '%s', current value: '%s' set by '%s'\n",
Prefix+strings.ToUpper(vv.name), vv.name, vv.name, *(vv.target), vv.setter)
prefix+strings.ToUpper(vv.name), vv.name, vv.name, *(vv.target), vv.setter)
}
}
fmt.Fprintln(os.Stderr)
flag.Usage()
os.Exit(2)
return
}
typ = "Required"
}
if *showSettings {
if *(v.target) != "" && vars.vv[vi].setter != goInit {
fmt.Fprintf(os.Stdout, "%s setting from '%s' is: '%s'\n",
typ, vars.vv[vi].setter, *(v.target))
}
}
}
}