ParseString parses a given string, calls replace var on found variables and returns the replaced string
(value string, replace ReplaceVarFn)
| 13 | |
| 14 | // ParseString parses a given string, calls replace var on found variables and returns the replaced string |
| 15 | func ParseString(value string, replace ReplaceVarFn) (interface{}, error) { |
| 16 | if value == "" { |
| 17 | return value, nil |
| 18 | } |
| 19 | |
| 20 | matches := VarMatchRegex.FindAllStringIndex(value, -1) |
| 21 | |
| 22 | // No vars found |
| 23 | if len(matches) == 0 { |
| 24 | return value, nil |
| 25 | } |
| 26 | |
| 27 | newValue := value[:matches[0][0]] |
| 28 | forceString := false |
| 29 | for index, match := range matches { |
| 30 | var ( |
| 31 | matchStr = value[match[0]:match[1]] |
| 32 | newMatchStr string |
| 33 | ) |
| 34 | |
| 35 | if matchStr[0] == '$' && matchStr[1] == '$' { |
| 36 | newMatchStr = matchStr[1:] |
| 37 | } else { |
| 38 | offset := 2 |
| 39 | if matchStr[1] == '!' { |
| 40 | offset = 3 |
| 41 | forceString = true |
| 42 | } |
| 43 | |
| 44 | replacedValue, err := replace(matchStr[offset : len(matchStr)-1]) |
| 45 | if err != nil { |
| 46 | return "", err |
| 47 | } |
| 48 | |
| 49 | switch v := replacedValue.(type) { |
| 50 | case string: |
| 51 | newMatchStr = v |
| 52 | default: |
| 53 | if forceString || len(matchStr) != len(value) { |
| 54 | newMatchStr = fmt.Sprintf("%v", v) |
| 55 | } else { |
| 56 | return v, nil |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | newValue += newMatchStr |
| 62 | if index+1 >= len(matches) { |
| 63 | newValue += value[match[1]:] |
| 64 | } else { |
| 65 | newValue += value[match[1]:matches[index+1][0]] |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | return newValue, nil |
| 70 | } |