https://play.golang.org/p/xJN8MHWIHwI
Resolve bash/shell variables. Format variables as in bash\shell
TODO:
- default value
${A:-default value}
https://play.golang.org/p/xJN8MHWIHwI
Resolve bash/shell variables. Format variables as in bash\shell
TODO:
${A:-default value}
package main | |
import ( | |
"bytes" | |
"fmt" | |
) | |
func main() { | |
params := map[string]string{ | |
"a": "1", | |
"b": "2", | |
} | |
fmt.Println(Format("a=${a} b=${b} c=${c} d=${d}", params)) | |
} | |
func Format(format string, params map[string]string) string { | |
if params == nil { | |
params = map[string]string{} | |
} | |
buf := new(bytes.Buffer) | |
entered := false | |
start := 0 | |
for pos, char := range format { | |
switch char { | |
case '$': | |
if format[pos+1] == '{' { | |
entered = true | |
start = pos + 2 | |
} | |
case '}': | |
if entered { | |
paramName := format[start:pos] | |
entered = false | |
buf.WriteString(params[paramName]) | |
} | |
default: | |
if !entered { | |
buf.WriteRune(char) | |
} | |
} | |
} | |
return buf.String() | |
} |