/
markdown.go
67 lines (53 loc) · 1.21 KB
/
markdown.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package markdown
import (
"bytes"
"fmt"
"github.com/longbridgeapp/autocorrect"
"github.com/microcosm-cc/bluemonday"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
)
var md goldmark.Markdown
func init() {
md = goldmark.New(
goldmark.WithExtensions(extension.GFM),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
parser.WithAttribute(),
),
goldmark.WithRendererOptions(
html.WithUnsafe(),
// don’t using html.WithHardWraps
),
)
}
// Options with markdown parser
type Options struct {
Format bool
}
// Parse markdown convert to html
func Parse(content string, option ...Options) (string, error) {
opt := Options{
Format: true,
}
if len(option) > 0 {
opt = option[0]
}
buf := new(bytes.Buffer)
err := md.Convert([]byte(content), buf)
if err != nil {
return "", fmt.Errorf("markdown convert failed, err: %+v", err)
}
html := buf.String()
if opt.Format {
html, err = autocorrect.FormatHTML(html)
if err != nil {
return "", fmt.Errorf("format markdown html failed, err: %+v", err)
}
}
// scrub content of XSS
html = bluemonday.UGCPolicy().Sanitize(html)
return html, nil
}