V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
godlovesxcjtest
V2EX  ›  Go 编程语言

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

  •  
  •   godlovesxcjtest · 2022-05-04 10:51:17 +08:00 · 2169 次点击
    这是一个创建于 716 天前的主题,其中的信息可能已经有所发展或是发生改变。

    模板代码如下:

    {{- 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 。

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

    8 条回复    2022-05-04 13:05:42 +08:00
    godlovesxcjtest
        1
    godlovesxcjtest  
    OP
       2022-05-04 10:51:34 +08:00
    求助大家,这个问题困扰了我好几天了
    nanmu42
        2
    nanmu42  
       2022-05-04 10:55:56 +08:00 via iPhone
    html/template 自带防注入,会转义内容。

    你可能要用它的兄弟 text/template ,注意不要用它直接处理用户输入。
    godlovesxcjtest
        3
    godlovesxcjtest  
    OP
       2022-05-04 10:56:00 +08:00
    是尖括号 "<" 变成了 &lt
    pigmen
        4
    pigmen  
       2022-05-04 10:59:27 +08:00
    使用 text/template
    godlovesxcjtest
        5
    godlovesxcjtest  
    OP
       2022-05-04 11:04:02 +08:00
    是的,我知道 html/template 会转义内容,防止注入。但是我不理解的是,为什么把我在模板里定义的内容也给转义了,这不是模板的输入啊。html/template 的文档里应该写着只会转义模板的输入
    @nanmu42 @pigmen
    mengyx
        6
    mengyx  
       2022-05-04 11:37:46 +08:00 via Android   ❤️ 1
    因为你这个“<?xml”是 xml 的 header ,不符合 html 语法。要么你不要使用 html/template 去处理,要么 execute 之后手动添加
    input2output
        7
    input2output  
       2022-05-04 12:24:37 +08:00   ❤️ 1
    换成:
    {{- printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }}
    godlovesxcjtest
        8
    godlovesxcjtest  
    OP
       2022-05-04 13:05:42 +08:00
    @mengyx 感谢!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2627 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 01:48 · PVG 09:48 · LAX 18:48 · JFK 21:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.