-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringresolver.go
48 lines (45 loc) · 1.11 KB
/
stringresolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package dynamictags
import (
"errors"
"fmt"
"os"
"strings"
)
const (
START_INCLUDE = "${"
END_INCLUDE = "}"
)
// Process string. Replace ${ENVIRONMENT_VARIABLE} by value from dictionary or by
// environment variable if no dictionary value found or replace by empty string
// if no dictionary and no environment variable found
// Parameters:
// - str source string
// - dictionary dictionary
//
// Returns:
// - result string or error
func ProcessString(str string, dictionary map[string]string) (string, error) {
stIndx := strings.Index(str, START_INCLUDE)
if stIndx < 0 {
return str, nil
}
endIndx := strings.LastIndex(str, END_INCLUDE)
if endIndx < 0 || endIndx < stIndx {
msg := fmt.Sprintf("incorrect tag structure. String '%s'. No closed brace", str)
return "", errors.New(msg)
}
contentStr := str[stIndx+len(START_INCLUDE) : endIndx]
content, err := ProcessString(contentStr, dictionary)
if err != nil {
return "", err
}
val, ok := dictionary[content]
if !ok {
val, ok = os.LookupEnv(content)
if !ok {
val = ""
}
}
res := str[:stIndx] + val + str[endIndx+1:]
return res, nil
}