go语言 html template,如何摆脱Golang中的html/template中的ZgotmplZ?

本文介绍了Go的html/template库中遇到的特殊值`ZgotmplZ`,它表示输入内容在运行时可能触發了CSS或URL过滤。通过使用`template.URL`类型或自定义函数如`safeURL`可以确保URL的安全插入。示例代码展示了如何避免`ZgotmplZ`错误,确保模板安全执行。
摘要由CSDN通过智能技术生成

ZgotmplZ是一个特殊值,表示您的输入无效。从html/template的文档引用:

"ZgotmplZ" is a special value that indicates that unsafe content reached a

CSS or URL context at runtime. The output of the example will be

#ZgotmplZ

If the data comes from a trusted source, use content types to exempt it

from filtering: URL(`javascript:...`).

如果你想替换一个有效 URL文本,没有什么特别喜欢像需要safeURL功能。如果您的模板执行结果的值为"#ZgotmplZ",则表示您要插入的网址无效。

见这个例子:

t := template.Must(template.New("").Parse(`` + "\n"))

t.Execute(os.Stdout, "http://google.com")

t.Execute(os.Stdout, "badhttp://google.com")

输出:

,如果你想使用URL作为,是不逃避您可以使用template.URL类型的值。请注意,在这种情况下,即使它不是有效的URL,所提供的值也会按原样使用。

safeURL不是某种可用于模板的魔术或预定义函数。但是,你可以注册一个返回string URL参数作为template.URL类型的值,你自己的自定义功能:

t2 := template.Must(template.New("").Funcs(template.FuncMap{

"safeURL": func(u string) template.URL { return template.URL(u) },

}).Parse(`` + "\n"))

t2.Execute(os.Stdout, "http://google.com")

t2.Execute(os.Stdout, "badhttp://google.com")

输出:

注:如果你能在template.URL传递值不需要注册并使用safeURL()定制功能:

t3 := template.Must(template.New("").Parse(`` + "\n"))

t3.Execute(os.Stdout, template.URL("http://google.com"))

t3.Execute(os.Stdout, template.URL("badhttp://google.com"))

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值