GoTemplate attempts to substitute the given payload into the given template using Go's templating syntax. TODO: memoize templates for memory efficiency?
(in string, payload types.MessagePayload, extraFuncs template.FuncMap)
| 16 | // GoTemplate attempts to substitute the given payload into the given template using Go's templating syntax. |
| 17 | // TODO: memoize templates for memory efficiency? |
| 18 | func GoTemplate(in string, payload types.MessagePayload, extraFuncs template.FuncMap) (string, error) { |
| 19 | tmpl, err := template.New("text"). |
| 20 | Funcs(extraFuncs). |
| 21 | // text/template substitutes a missing label with "<no value>". |
| 22 | // NOTE: html/template does not, for obvious reasons. |
| 23 | Option("missingkey=invalid"). |
| 24 | Parse(in) |
| 25 | if err != nil { |
| 26 | return "", xerrors.Errorf("template parse: %w", err) |
| 27 | } |
| 28 | |
| 29 | var out strings.Builder |
| 30 | if err = tmpl.Execute(&out, payload); err != nil { |
| 31 | return "", xerrors.Errorf("template execute: %w", err) |
| 32 | } |
| 33 | |
| 34 | return out.String(), nil |
| 35 | } |