duanlangwen9597 2015-07-02 06:52
浏览 347

如何在Go中转义原始HTML?

I have managed to output text using the following line:

fmt.Fprintf(w, "<p>some text</p>")

But this will literally output the HTML tags. How do you output it so it can safely be included in HTML like you would with echo in PHP?

  • 写回答

2条回答 默认 最新

  • doujing1156 2015-07-02 08:13
    关注

    fmt.Fprintf() has no knowledge of HTML syntax: it outputs raw data without escaping it (it may do some formatting but that is not escaping).

    You don't use it correctly though: its second parameter is a format string, so you should call it rather like this:

    fmt.Fprintf(w, "%s", "<p>some text</p>")
    

    Else if your text contains some format-specific special characters, you will not get the expected result.

    What you want is to escape HTML code so it can be safely included in HTML documents/pages. For that you get excellent support from the html/template package which provides you a powerful template engine where automatic escaping functionality being just one feature.

    Here's a simple example how to achieve what you want:

    w := os.Stdout
    
    text := "<p>some text</p>"
    fmt.Fprintf(w, "%s
    ", text)
    
    tt := `{{.}}`
    t := template.Must(template.New("test").Parse(tt))
    t.Execute(w, text)
    

    Output (try it on the Go Playground):

    <p>some text</p>
    &lt;p&gt;some text&lt;/p&gt;
    

    Also note that if you only want to escape some HTML code, there is a template.HTMLEscaper() function for that:

    fmt.Println(template.HTMLEscaper(text))
    

    Output:

    &lt;p&gt;some text&lt;/p&gt;
    
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失