您现在的位置是:网站首页> 编程资料编程资料
go语言实现markdown解析库的方法示例_Golang_
2023-05-26
393人已围观
简介 go语言实现markdown解析库的方法示例_Golang_
Blackfriday是在Go中实现的Markdown处理器。您可以安全地输入用户提供的数据,速度快,支持通用扩展(表,智能标点符号替换等),并且对于所有utf-8(unicode)都是安全的输入。
当前支持HTML输出以及Smartypants扩展。
使用
首先当然要引入:
import github.com/russross/blackfriday
然后
output := blackfriday.MarkdownBasic(input)
这里input是[]byte类型,可以将markdown类型的字符串强转为[]byte,即input = []byte(string)
如果想过滤不信任的内容,使用以下方法:
代码:
package main import ( "fmt" "github.com/microcosm-cc/bluemonday" "github.com/russross/blackfriday" ) func main() { input := []byte("### 5lmh.com是个不错的go文档网站") unsafe := blackfriday.MarkdownCommon(input) html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) fmt.Println(string(html)) } 基本上就这些操作
我的使用方法是在添加新文章时,将表单提交的数据直接通过上面的方法转换后,将markdown和转换后的内容都存储到数据库中
不过我在前端渲染时,又出现了问题,就是转换后的内容中的html标签会直接显示在网页上,为避免这种状况,我使用了自定义模板函数
// 定义模板函数 func unescaped(x string) interface{} { return template.HTML(x)} // 注册模板函数 t := template.New("post.html") t = t.Funcs(template.FuncMap{"unescaped": unescaped}) t, _ = t.ParseFiles("templates/post.html") t.Execute(w, post) // 使用模板函数 {{ .Content|unescaped }} 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- golang 生成二维码海报的实现代码_Golang_
- 如何控制Go编码JSON数据时的行为(问题及解决方案)_Golang_
- GoLang 逃逸分析的机制详解_Golang_
- golang之JWT实现的示例代码_Golang_
- 浅谈Golang是如何读取文件内容的(7种)_Golang_
- golang如何优雅的编写事务代码示例_Golang_
- 解决 Golang VS Code 插件下载安装失败的问题_Golang_
- 一文了解Go语言中编码规范的使用_Golang_
- GO 使用Webhook 实现github 自动化部署的方法_Golang_
- viper配置框架的介绍支持zookeeper的读取和监听_Golang_
