如何在用户帖子中呈现带有链接但没有其他HTML的内容?

huangapple go评论83阅读模式
英文:

How to render user posts with links but no other html?

问题

我正在构建一个类似于Twitter的网站。用户可以发布帖子并使用@用户名的格式提及其他用户。

起初,我打算在服务器端解析每个帖子,并在@提及周围添加HTML标签,然后将帖子呈现为template.HTML(我在服务器端使用的是Go语言)。但后来我意识到用户可以添加任何他们想要的HTML,而我不希望出现这种情况。有没有一种方法可以将帖子呈现为HTML,同时忽略用户尝试上传的任何HTML?他们上传的任何代码/标记都应该以纯文本形式显示。

或者,使用JavaScript在客户端的@提及周围添加标记会更好吗?

英文:

I'm building a website similar to twitter. A user can make a post and mention another user using the @username notation.

At first I was going to parse each post server side and add html tags around the @mentions, then render the post as a template.HTML (I'm using Go server side), but then I realized that users would be able to add any html they want, and I don't want that. Is there a way to render the posts as html while ignoring any html that the user tries to upload? Any code/markup that they upload should be shown in plain text.

Or will it be better to add the markup around the @mentions client side using javascript?

答案1

得分: 2

太担心了!用户输入的这种HTML注入是一个真正的问题,幸运的是,有一个简单的解决方法,你可以转义HTML字符,这样浏览器就能理解文本中的字面"<"字符,而不是HTML元素的开始。

在Go语言中,有一个html.EscapeString函数,你可以将用户输入传递给它,然后可以安全地在HTML中使用。因此,你可以对输入进行清理,然后解析并链接@mentions

英文:

Great worry! This type of HTML injection from user input is a real problem, fortunately, there’s an easy fix, you can escape HTML characters so the browser understands that there’s a literal “<“ character in the text, not the start of a HTML element.

In Go, there’s the html.EscapeString, which you pass the user input and then can safely use inside HTML. So you would sanitize the input and after that parse it and link the @mentions.

huangapple
  • 本文由 发表于 2022年6月19日 10:09:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72673854.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定