运行时错误:在使用模板的Martini中,内存地址无效或空指针解引用。

huangapple go评论77阅读模式
英文:

runtime error: invalid memory address or nil pointer dereference in martini with template

问题

这是我的代码:

m.Get("/", func(r render.Render) string {
    t := template.New("some template")
    toto := "titi"
    templateh := "<html>Hello world! {{ toto }} <form name='input' action='../first' method='post' ><input type='texte' name='toto'><input type='submit' value='Submit'></form></html>"
    t, _ = t.Parse(templateh)
    var doc bytes.Buffer
    err := t.Execute(&doc, toto)
    if err != nil {
        fmt.Println("There was an error:", err)
    }
    s := doc.String()
    fmt.Println(s)

    return s
})

它返回一个运行时错误:无效的内存地址或空指针解引用。我不明白为什么会出现这个错误...

英文:

here is my code :

m.Get(&quot;/&quot;, func(r render.Render) string {
	t := template.New(&quot;some template&quot;)
	toto := &quot;titi&quot;
	templateh := &quot;&lt;html&gt;Hello world! {{ toto }} &lt;form name=&#39;input&#39; action=&#39;../first&#39; method=&#39;post&#39; &gt;&lt;input type=&#39;texte&#39; name=&#39;toto&#39;&gt;&lt;input type=&#39;submit&#39; value=&#39;Submit&#39;&gt;&lt;/form&gt;&lt;/html&gt;&quot;
	t, _ = t.Parse(templateh)
	var doc bytes.Buffer
	err := t.Execute(&amp;doc, toto)
	if err != nil {
		fmt.Println(&quot;There was an error:&quot;, err)
	}
	s := doc.String()
	fmt.Println(s)

	return s

})

and it returns me a runtime error: invalid memory address or nil pointer dereference

and i don't understand why ...

答案1

得分: 4

调用

    t, _ = t.Parse(templateh)

返回nil和一个错误,错误说明函数"todo"未定义。模板的Execute方法对nil指针进行解引用,导致恐慌。

你应该做两件事:

  • 检查和处理解析调用的错误返回。这是使用template.Must辅助函数的好地方。
  • 通过将{{ todo }}替换为{{.}}来修复模板。
英文:

The call

    t, _ = t.Parse(templateh)

returns the nil and error an error stating that the function "todo" is not defined. The template Execute method dereferences the nil pointer, resulting in the panic.

You should change two things:

  • Check and handle the error return from the parse call. This is a good place to use the template.Must helper function.
  • Fix the template by replacing {{ todo }} with {{.}}

huangapple
  • 本文由 发表于 2014年9月16日 07:44:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/25858592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定