github.com/Jeffail/benthos/v3@v3.65.0/lib/util/text/env_vars.go (about) 1 package text 2 3 import ( 4 "bytes" 5 "os" 6 "regexp" 7 "strings" 8 ) 9 10 //------------------------------------------------------------------------------ 11 12 var ( 13 envRegex = regexp.MustCompile(`\${[0-9A-Za-z_.]+(:((\${[^}]+})|[^}])+)?}`) 14 escapedEnvRegex = regexp.MustCompile(`\${({[0-9A-Za-z_.]+(:((\${[^}]+})|[^}])+)?})}`) 15 ) 16 17 // ContainsEnvVariables returns true if inBytes contains environment variable 18 // replace patterns. 19 func ContainsEnvVariables(inBytes []byte) bool { 20 return envRegex.Find(inBytes) != nil || escapedEnvRegex.Find(inBytes) != nil 21 } 22 23 // ReplaceEnvVariables will search a blob of data for the pattern `${FOO:bar}`, 24 // where `FOO` is an environment variable name and `bar` is a default value. The 25 // `bar` section (including the colon) can be left out if there is no 26 // appropriate default value for the field. 27 // 28 // For each aforementioned pattern found in the blob the contents of the 29 // respective environment variable will be read and will replace the pattern. If 30 // the environment variable is empty or does not exist then either the default 31 // value is used or the field will be left empty. 32 func ReplaceEnvVariables(inBytes []byte) []byte { 33 replaced := envRegex.ReplaceAllFunc(inBytes, func(content []byte) []byte { 34 var value string 35 if len(content) > 3 { 36 if colonIndex := bytes.IndexByte(content, ':'); colonIndex == -1 { 37 value = os.Getenv(string(content[2 : len(content)-1])) 38 } else { 39 targetVar := content[2:colonIndex] 40 defaultVal := content[colonIndex+1 : len(content)-1] 41 42 value = os.Getenv(string(targetVar)) 43 if value == "" { 44 value = string(defaultVal) 45 } 46 } 47 // Escape newlines, otherwise there's no way that they would work 48 // within a config. 49 value = strings.ReplaceAll(value, "\n", "\\n") 50 } 51 return []byte(value) 52 }) 53 replaced = escapedEnvRegex.ReplaceAll(replaced, []byte("$$$1")) 54 return replaced 55 } 56 57 //------------------------------------------------------------------------------