0

I am trying to make a simple webserver an decided to use bone for my routes and Gorilla csrf for csrf. The problem I am having is that I cannot save the csrf.TemplateField(req) in a struct to use in a template.

Imports:

import (
    "database/sql"
    "net/http"
    "text/template"

    "github.com/go-zoo/bone"
    "github.com/gorilla/csrf"
)

Struc:

type Input struct {
    Title     string
    Name      string
    csrfField template.HTML // Error here: Undefined "text/template".HTML
}

Handler Code:

func RootHandler(rw http.ResponseWriter, req *http.Request) {
    temp, _ := template.ParseFiles("site/index.html")
    head := Input{Title: "test", csrf.TemplateTag: csrf.TemplateField(req)}
    temp.Execute(rw, head)
}

I have tried changing the template.HTML type to string and then I got an error with csrf.TemplateField(req):

unknown field 'csrf.TemplateTag' in struct literal of type Input

So can anybody help? Am I using the wrong type?

2
  • Change csrf.TemplateTag to csrfField. Make sure csrf.TemplateField(req) is type template.HTML Commented May 9, 2018 at 21:19
  • @Godfrey Thank you I changed csrf.Template Tag to CSRFField and in the struc I changed csrfField to CSRFField Commented May 9, 2018 at 21:23

2 Answers 2

3

The HTML type is declared in "html/template" . Import "html/template" instead of "text/template".

The template engine ignores unexported fields. Export the field name by starting the name with an uppercase character.

import (
    "database/sql"
    "net/http"
    "html/template"

    "github.com/go-zoo/bone"
    "github.com/gorilla/csrf"
)
Struc:

type Input struct {
    Title     string
    Name      string
    CSRFField template.HTML 
}
Sign up to request clarification or add additional context in comments.

Comments

2

From the second sentence of text/template documentation:

To generate HTML output, see package html/template, which has the same 
interface as this package but automatically secures HTML output against 
certain attacks.

text/template does not have an HTML method, thus you are receiving an undefined error.

Happy coding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.