go語言實現(xiàn)markdown解析庫的方法示例
Blackfriday是在Go中實現(xiàn)的Markdown處理器。您可以安全地輸入用戶提供的數(shù)據(jù),速度快,支持通用擴展(表,智能標點符號替換等),并且對于所有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))
}
基本上就這些操作
我的使用方法是在添加新文章時,將表單提交的數(shù)據(jù)直接通過上面的方法轉換后,將markdown和轉換后的內容都存儲到數(shù)據(jù)庫中
不過我在前端渲染時,又出現(xiàn)了問題,就是轉換后的內容中的html標簽會直接顯示在網頁上,為避免這種狀況,我使用了自定義模板函數(shù)
// 定義模板函數(shù)
func unescaped(x string) interface{} { return template.HTML(x)}
// 注冊模板函數(shù)
t := template.New("post.html")
t = t.Funcs(template.FuncMap{"unescaped": unescaped})
t, _ = t.ParseFiles("templates/post.html")
t.Execute(w, post)
// 使用模板函數(shù)
{{ .Content|unescaped }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Golang實現(xiàn)帶優(yōu)先級的select
這篇文章主要為大家詳細介紹了如何在Golang中實現(xiàn)帶優(yōu)先級的select,文中的示例代碼講解詳細,對我們學習Golang有一定的幫助,需要的可以參考一下2023-04-04

