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

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 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 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果