doubo1883
doubo1883
2018-05-09 21:10
浏览 54
已采纳

Golang CSRF在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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtntjwkl83750
    dtntjwkl83750 2018-05-09 21:16
    已采纳

    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 
    }
    
    点赞 评论
  • doufud21086
    doufud21086 2018-05-09 21:19

    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.

    点赞 评论

相关推荐