Skip to content

Instantly share code, notes, and snippets.

@gebv
Created September 12, 2021 22:36
Show Gist options
  • Save gebv/cc573026dd0e91bafab8144f07a3f108 to your computer and use it in GitHub Desktop.
Save gebv/cc573026dd0e91bafab8144f07a3f108 to your computer and use it in GitHub Desktop.
Resolve bash/shell variables. Format variables as in bash\shell
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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment