Go 的 html/template 把我的模板自动给转码了

2022-05-04 10:51:17 +08:00
 godlovesxcjtest

模板代码如下:

{{- define "common/web/atom"}}
<?xml version="1.0" encoding="utf-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom">

    </feed>
{{end}}

很简单的一个代码,主要是想用来实现一个 atom 服务器,返回浏览器 atom.xml 文件

但是调用 ExecuteTemplate 方法后,变成了这个样子:



&lt;?xml version="1.0" encoding="utf-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom">
     
    </feed>

尖括号"<" 变成了 <

很奇怪的一个问题。我知道 Go 的 html/template 会对一些输入进行转码,避免把用户的输入生成到 html 。

但是为什么会把我的模板里面的也进行转码了呢

2181 次点击
所在节点    Go 编程语言
8 条回复
godlovesxcjtest
2022-05-04 10:51:34 +08:00
求助大家,这个问题困扰了我好几天了
nanmu42
2022-05-04 10:55:56 +08:00
html/template 自带防注入,会转义内容。

你可能要用它的兄弟 text/template ,注意不要用它直接处理用户输入。
godlovesxcjtest
2022-05-04 10:56:00 +08:00
是尖括号 "<" 变成了 &lt
pigmen
2022-05-04 10:59:27 +08:00
使用 text/template
godlovesxcjtest
2022-05-04 11:04:02 +08:00
是的,我知道 html/template 会转义内容,防止注入。但是我不理解的是,为什么把我在模板里定义的内容也给转义了,这不是模板的输入啊。html/template 的文档里应该写着只会转义模板的输入
@nanmu42 @pigmen
mengyx
2022-05-04 11:37:46 +08:00
因为你这个“<?xml”是 xml 的 header ,不符合 html 语法。要么你不要使用 html/template 去处理,要么 execute 之后手动添加
input2output
2022-05-04 12:24:37 +08:00
换成:
{{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }}
godlovesxcjtest
2022-05-04 13:05:42 +08:00
@mengyx 感谢!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/850741

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX