Go转换Markdown为HTML

正文

安装依赖

1
go get github.com/russross/blackfriday

引用

1
import "github.com/russross/blackfriday"

简单测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package test

import (
"fmt"
"github.com/russross/blackfriday"
"testing"
)

// 普通的测试
func TestMd2HTML(t *testing.T) {
inputStr := `
# 一级标题
## 二级标题
`
output := blackfriday.MarkdownCommon([]byte(inputStr))
outputStr := string(output)
fmt.Println(outputStr)
}

结果会生成

1
2
3
<h1>一级标题</h1>

<h2>二级标题</h2>

读取文件

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
package test

import (
"fmt"
"github.com/russross/blackfriday"
"io/ioutil"
"os"
"testing"
)

func ReadAll(filePth string) ([]byte, error) {
f, err := os.Open(filePth)
if err != nil {
return nil, err
}
return ioutil.ReadAll(f)
}

func MdToHTML(md string) string {
output := blackfriday.MarkdownCommon([]byte(md))
outputStr := string(output)
return outputStr
}

// 普通的测试
func TestMd2HTML(t *testing.T) {
path := "D:\\Project\\myblog\\source\\_posts\\2024-02-21-go-md-html.md"
res, err := ReadAll(path)
if err != nil {
panic(err)
}
outputStr := MdToHTML(string(res))
fmt.Println(outputStr)
}