http - 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”
那么有人可以帮忙吗?我使用了错误的类型吗?
解决方案
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
}
推荐阅读
- excel - 如何使用文本计算excel中的行数
- python - 是什么阻止 python 识别我的相对路径?
- python - 将 Matplotlib 绘图标题放在右边距
- java - Firestore 时间戳到 ArrayList
然后到日期 - python - Pandas df中每个用户的两个事件行之间的时间差
- ag-grid - Angular 8 中的 ag-grid:自动调整列大小不适用于客户端页面
- c++ - 如何在 C++ 中定义常量 _DEBUG
- csv - 使用 beautifulsoup4 从网站中提取数据并解析为 csv
- prolog - 在 swi-prolog 的子句中使用 assertz
- cygwin - Windows 2000 上的 Cygwin