Search code examples
httpgowebservercsrfmux

Golang CSRF save template field in struct


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?


Solution

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