7

I'm sure this is just something dumb I'm doing, but I'm new to Go, so not sure what's going on here. I have the following basic setup.

requestHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    t := template.New("test")
    t, _ := template.ParseFiles("base.html")
    t.Execute(w, "")
})

server := &http.Server{
    Addr:           ":9999",
    Handler:        requestHandler,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}

log.Fatal(server.ListenAndServe())

The contents of base.html are as follows:

<DOCTYPE html>
<html>
    <body>
        base.html
    </body>
</html>

When I run the server and load the page, I see the HTML inside the template verbatim -- instead of the interpreted version. Turns out, the template is being wrapped in pre tags, and is subsequently being wrapped in a new document.

So what's going on? Why is go by default treating this as plain text rather than sending it over as html, so that the browser can render it properly? Surely this must be a simple misunderstanding, but not getting anything in searches. Ideas?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
meesterguyperson
  • 1,726
  • 1
  • 20
  • 31

1 Answers1

10

You need to add a header with the Content-Type

 w.Header().Set("Content-Type", "text/html")
fabrizioM
  • 46,639
  • 15
  • 102
  • 119
  • Ah, figured it might be something like that. And of course, the header needs to be set before writing anything, just for clarification. Thanks! – meesterguyperson Jul 31 '14 at 19:01
  • 6
    You actually don't need to do that (it's just helpful): Go and/or your browser will infer that for you. The OP is missing a `!` from his doctype declaration, which is why it renders as plain text: ` ` – elithrar Jul 31 '14 at 21:54
  • 1
    Okay, feeling kinda dumb now. :-) Why is every stinking character so darn important?! Nice catch. – meesterguyperson Aug 01 '14 at 12:36