How to use map key including - in template

I use a basic template OK until I have a map with key including - such ask {{.vars.X-test}}.

The template will crash. Does anyone ever a solution on this?

code struct
type Stack struct {
StepResult map[string]interface{}
vars := make(map[string]string, paramLen)
stack.StepResult[“vars”] = vars
vars[“X-test”] = “abc”

2.template function
func (stack Stack) QueryFromStepResult(template string) string {
tmpl, _ := template.New(“key”).Parse(template)
buf := new(bytes.Buffer)
tmpl.Execute(buf, stack.StepResult)
return buf.String()

3.crash when using function with {{.vars.X-test}}
runtime error: invalid memory address or nil pointer dereference
/usr/bin/go/src/text/template/exec.go:164 (0x9c1fba)
errRecover: panic(e)
/usr/bin/go/src/runtime/panic.go:838 (0x6366a6)
gopanic: done = runOpenDeferFrame(gp, d)
/usr/bin/go/src/runtime/panic.go:220 (0x64c835)
panicmem: panic(memoryError)
/usr/bin/go/src/runtime/signal_unix.go:818 (0x64c805)
sigpanic: panicmem()
/usr/bin/go/src/text/template/exec.go:215 (0x9c23ec)
(*Template).execute: if t.Tree == nil || t.Root == nil {
/usr/bin/go/src/text/template/exec.go:201 (0xb0a1d4)
(*Template).Execute: return t.execute(wr, data)
/code/go/tms-go-apihub/broker/hub/stack.go:26 (0xb0a0a7)
Stack.QueryFromStepResult: tmpl.Execute(buf, stack.StepResult)

Hi @wangbin ,

Assignments copy the value to be assigned, and so adding abc to vars has no effect on the value in StepResult[“vars”]:

stack.StepResult[“vars”] = vars
vars[“X-test”] = “abc”

Try reversing the sequence of assignments to vars and StepResult:

vars["X-test"] = "abc"
stack.StepResult["vars"] = vars

And a tip: use code fences when posting code, like so:

vars["X-test"] = "abc"
stack.StepResult["vars"] = vars

This retains indenting and adds syntax highlighting and makes your code easier to read.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.