From a11dccc37df31ca04fe2cc1c2175952cc1a0b636 Mon Sep 17 00:00:00 2001 From: Patrick D'appollonio Date: Fri, 26 Apr 2019 16:39:45 -0400 Subject: [PATCH] Add missing files. --- structs.go | 7 ++++ template_functions.go | 92 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 structs.go create mode 100644 template_functions.go diff --git a/structs.go b/structs.go new file mode 100644 index 0000000..8f67390 --- /dev/null +++ b/structs.go @@ -0,0 +1,7 @@ +package main + +type enotfounderr struct{ name string } + +func (e *enotfounderr) Error() string { + return "strict mode on: environment variable not found: $" + e.name +} diff --git a/template_functions.go b/template_functions.go new file mode 100644 index 0000000..c46c0d9 --- /dev/null +++ b/template_functions.go @@ -0,0 +1,92 @@ +package main + +import ( + "fmt" + "html/template" + "math/rand" + "os" + "strings" + "time" + "unsafe" +) + +var templateFunctions = template.FuncMap{ + "env": envfunc, + "raw": func(s string) string { + return s + }, + + "sprintf": func(s string, args ...interface{}) string { + return fmt.Sprintf(s, args...) + }, + + "envdefault": func(k, defval string) (string, error) { + s, err := envfunc(k) + + if err != nil { + if _, ok := err.(*enotfounderr); ok { + return defval, nil + } + + return "", err + } + + if s != "" { + return s, nil + } + + return defval, nil + }, + + "rndstring": rndgen, + "lowercase": strings.ToLower, + "uppercase": strings.ToUpper, + "title": strings.Title, +} + +func envfunc(k string) (string, error) { + k = strings.ToUpper(k) + + if v, found := os.LookupEnv(k); found { + return v, nil + } + + if v, found := envvars[k]; found { + return v, nil + } + + if strict { + return "", &enotfounderr{name: k} + } + + return "", nil +} + +// from: https://stackoverflow.com/a/31832326 + +var src = rand.NewSource(time.Now().UnixNano()) + +const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +const ( + letterIdxBits = 6 // 6 bits to represent a letter index + letterIdxMask = 1<= 0; { + if remain == 0 { + cache, remain = src.Int63(), letterIdxMax + } + if idx := int(cache & letterIdxMask); idx < len(letterBytes) { + b[i] = letterBytes[idx] + i-- + } + cache >>= letterIdxBits + remain-- + } + + return *(*string)(unsafe.Pointer(&b)) +}