/
markdown_content.go
108 lines (84 loc) · 2.03 KB
/
markdown_content.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package md2html
import (
"bytes"
"log"
"strings"
fm "github.com/adrg/frontmatter"
"github.com/ansidev/md2html/utils"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/parser"
)
type markdownContent struct {
meta map[string]interface{}
content string
}
func newMarkdownContent(bytes []byte, excerptSeparator string) (*markdownContent, error) {
frontmatter := make(map[string]interface{})
contentBytes, err := fm.Parse(strings.NewReader(string(bytes)), &frontmatter)
if err != nil {
return nil, err
}
hasTitle := true
if t, ok := frontmatter["title"]; !ok {
hasTitle = false
} else {
t1, ok := t.(string)
if !ok || len(t1) == 0 {
hasTitle = false
}
}
content := string(contentBytes)
if !hasTitle {
frontmatter["title"] = utils.GetFirstLine(content)
}
mdc := &markdownContent{frontmatter, content}
if len(excerptSeparator) == 0 {
return mdc, nil
}
contentSlice := strings.Split(content, excerptSeparator)
if len(contentSlice) == 0 {
return mdc, nil
}
frontmatter["excerpt"] = utils.TrimAllLineEndingChars(contentSlice[0])
content = strings.Join(contentSlice[1:], excerptSeparator)
return &markdownContent{frontmatter, content}, nil
}
func (c *markdownContent) frontmatter() map[string]interface{} {
return c.meta
}
func (c *markdownContent) field(key string) interface{} {
if key == "title" {
return c.title()
}
if val, ok := c.meta[key]; ok {
return val
}
return nil
}
func (c *markdownContent) title() string {
if val, ok := c.meta["title"]; ok {
title, ok1 := val.(string)
if ok1 {
return title
}
}
return ""
}
func (c *markdownContent) markdown() string {
return utils.TrimBlankLines(c.content)
}
func (c *markdownContent) html() string {
markdownBytes := []byte(c.content)
mdconv := goldmark.New(
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
)
var buf bytes.Buffer
if err := mdconv.Convert(markdownBytes, &buf); err != nil {
log.Fatal(err)
return ""
}
s := strings.TrimSuffix(buf.String(), "\n")
return strings.ReplaceAll(s, "\n", utils.EOL())
}