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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程