An example of implementation of markdown parsing library with go language

Time:2020-11-7

Blackfriday is a markdown processor implemented in go. You can input user provided data safely, fast, support universal extensions (tables, smart punctuation replacement, etc.), and it is safe input for all UTF-8 (Unicode).

Currently, HTML output and smartypants extension are supported.

use

First of all, of course, we should introduce:


import github.com/russross/blackfriday

then


output := blackfriday.MarkdownBasic(input)

Here, input is of type [] byte, and string of markdown type can be forced to be [] byte, that is, input = [] byte (string)

If you want to filter untrusted content, use the following method:

code:

package main

import (
  "fmt"

  "github.com/microcosm-cc/bluemonday"
  "github.com/russross/blackfriday"
)

func main() {
  input := []byte("### 5 lmh.com It's a good go document website
  unsafe := blackfriday.MarkdownCommon(input)
  html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
  fmt.Println(string(html))
}

These are basically the operations

When I add a new article, I convert the data submitted by the form directly through the above method, and store both the markdown and the converted content in the database

However, when I render in the front end, there is another problem, that is, the HTML tags in the converted content will be directly displayed on the web page. To avoid this situation, I use the custom template function

//Defining template functions
  func unescaped(x string) interface{} { return template.HTML(x)}

  //Register template functions
  t := template.New("post.html")
  t = t.Funcs(template.FuncMap{"unescaped": unescaped})
  t, _ = t.ParseFiles("templates/post.html")
  t.Execute(w, post)

  //Using template functions

  {{ .Content|unescaped }}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

The road of high salary, a more complete summary of MySQL high performance optimization in history

preface MySQL for many linux practitioners, is a very difficult problem, most of the cases are because of the database problems and processing ideas are not clear. Before the optimization of MySQL, we must understand the query process of MySQL. In fact, a lot of query optimization work is to follow some principles so that […]