go语言实现markdown解析库

栏目: IT技术 · 发布时间: 6年前

内容简介:Blackfriday是在Go中实现的Markdown处理器。您可以安全地输入用户提供的数据,速度快,支持通用扩展(表,智能标点符号替换等),并且对于所有utf-8(unicode)都是安全的输入。** 文章转自go语言中文文档当前支持HTML输出以及Smartypants扩展。

Blackfriday是在 Go 中实现的Markdown处理器。您可以安全地输入用户提供的数据,速度快,支持通用扩展(表,智能标点符号替换等),并且对于所有utf-8(unicode)都是安全的输入。

** 文章转自go语言中文文档 http://www.topgoer.com **

当前支持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 }}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Database Design and Implementation

Database Design and Implementation

Edward Sciore / Wiley / 2008-10-24 / 1261.00 元

* Covering the traditional database system concepts from a systems perspective, this book addresses the functionality that database systems provide as well as what algorithms and design decisions will......一起来看看 《Database Design and Implementation》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器