3

I come to a very bothering problem, And it took me about an hour to figure what cause the problem, but I don't know why:

I am using html/template to rending a web page and the code is like this:

t, _ := template.parseFiles("template/index.tmpl")
...
t.Execute(w, modelView) // w is a http.ResponseWriter and modelView is a data struct.

But unconsciously, I made a mistake that leave a <textarea> tag open:

<html>
<body>
        <form id="batchAddUser" class="form-inline">
        **this one**  -->  <textarea name="users" value="" row=3 placeholder="input username and password splited by space">
            <button type="submit" class="btn btn-success" >Add</button>
        </form>
</body>
</html>

And then Go gives no exception and other hint, but just give a blank page with nothing, and the status code is 200.

It toke effect to locate the problem since no information was offered, but why is that happen? How comes a un-colsed tag cause problem like that? And how to debug that?

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
armnotstrong
  • 8,605
  • 16
  • 65
  • 130

2 Answers2

6

It is telling you about the error, you are just ignoring it.

If you look at the error returned by Execute, it tells you that your html is bad.

You should always check for errors. Something like:

t, err := template.New("test").Parse(ttxt)
if err != nil { 
    ...do something with error...
}
err = t.Execute(os.Stdout, nil) // w is a http.R
if err != nil { 
    ...do something with error...
}

Here it is (with error printing) on Playground

Here it is, fixed on Playground

David Budworth
  • 11,248
  • 1
  • 36
  • 45
  • 2
    Note that catching the error from `t.Execute` puts you in a tricky spot - it's too late to actually show the user an error since the http.ResponseWriter has already been written too. The common way to deal with this is to create buffer pool that you write to (and if it fails, send a HTTP 500) and then `io.Copy(w, bufpool)` to write the executed template out. – elithrar Mar 15 '15 at 01:47
3

The Go's template package provides method Must that will make your program fail fast by panicking in case of such errors. You can free your code of some error checks, yet you will still be in control.

t := template.Must(template.parseFiles("template/index.tmpl"))
Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105