2

I am working in a Golang project, currently am trying to render some templates but the HTML code of the template is being printed in the browser. My project structure is:

|-app
|---models
|---controller
|---templates
|------index.gohtml
|-main.go

Then, the code that I have in one controller, to render the template is:

func Index(w http.ResponseWriter, req *http.Request, ps httprouter.Params){
    var tpl *template.Template
    tpl = template.Must(template.ParseGlob("app/templates/*.gohtml"))

    err := tpl.ExecuteTemplate(w, "index.gohtml", nil)

    if(err!=nil){
        fmt.Println("error:",err.Error())
    }

However I am not getting any error. But in the browser the code that I have inside index.gohtml is being printed and not rendered }

Sredny M Casanova
  • 4,735
  • 21
  • 70
  • 115
  • what if you replace `index.gohtml` with `app/templates/index.gohtml`? – Albert221 Aug 02 '17 at 19:27
  • @Albert221 the same, at first I had in that way but I get the same – Sredny M Casanova Aug 02 '17 at 19:29
  • I've only ever used `template.ParseFiles`, but it should work the same. If it is printing the html, then I guess it is parsing. Strange – RayfenWindspear Aug 02 '17 at 19:33
  • 2
    Are you using the route that `Index()` is registered as the handler for? You may just be serving the template file instead of executing the handler. – Adrian Aug 02 '17 at 19:41
  • 1
    I added the header "Content-Type", "text/html" and now it's rendering pretty well. However, I don't think that it should be the solution. As I know, this is somethings that is infered by Go – Sredny M Casanova Aug 02 '17 at 19:55
  • @Adrian I get your idea, but no, I am not serving the file – Sredny M Casanova Aug 02 '17 at 19:56
  • @SrednyMCasanova inferred from what? When you render a template, you're writing raw bytes to the response. It would have to parse the body to infer the type, which would be terrible for performance. – Adrian Aug 02 '17 at 19:58
  • @Adrian ok, I just read this post [look at the answer that says:](https://stackoverflow.com/questions/25066071/golang-html-output-is-being-interpreted-as-plain-text-instead-of-being-received) You actually don't need to do that (it's just helpful): Go and/or your browser will infer that for you. – Sredny M Casanova Aug 02 '17 at 20:05
  • 1
    They will do their best but won't necessarily be correct, and will be far, far less efficient and accurate trying to read and parse the content and guess the content type than if you just provide the correct content type since you already know it. – Adrian Aug 02 '17 at 20:09

1 Answers1

0

checkout net/http/sniff.go. It shows how net/http infers MIME types.

For Html your content can start with :

  • <!DOCTYPE HTML
  • <HTML
  • <HEAD
  • <SCRIPT
  • <IFRAME
  • <H1
  • <DIV
  • <FONT
  • <TABLE
  • <A
  • <STYLE
  • <TITLE
  • <B
  • <BODY
  • <BR
  • <P
  • <!--
R Menke
  • 8,183
  • 4
  • 35
  • 63