Search code examples
gomartini

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


here is my code :

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

})

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

and i don't understand why ...


Solution

  • 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 {{.}}