首页 > 解决方案 > Golang CSRF在struct中保存模板字段

问题描述

我正在尝试制作一个简单的网络服务器,并决定将bone用于我的路线,将 Gorilla csrf用于 csrf。我遇到的问题是我无法将 csrf.TemplateField(req) 保存在结构中以在模板中使用。

进口:

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

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

结构:

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

处理程序代码:

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

我尝试将 template.HTML 类型更改为字符串,然后 csrf.TemplateField(req) 出现错误:

输入类型的结构文字中的未知字段“csrf.TemplateTag”

那么有人可以帮忙吗?我使用了错误的类型吗?

标签: httpgowebservercsrfmux

解决方案


HTML类型在 "html/template" 中声明。导入“html/template”而不是“text/template”。

模板引擎会忽略未导出的字段。通过以大写字符开头的名称来导出字段名称。

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 
}

推荐阅读